<?php

namespace Tobuli\Services;

use Illuminate\Support\Facades\File;
use Tobuli\Entities\Device;
use Tobuli\Entities\DeviceGroup;
use Tobuli\Entities\User;
use Facades\Server;

class DeviceService
{
    public function addUser(Device $device, $user, $group = null) {
        $user_id = $user instanceof User ? $user->id : (int)$user;
        $group_id = $group instanceof DeviceGroup ? $group->id : (int)$group;

        $device->users()->sync([
            $user_id => [
                'group_id' => empty($group_id) ? null : $group_id
            ]
        ], false);
    }

    public function removeUser(Device $device, $user) {
        $user_id = $user instanceof User ? $user->id : (int)$user;

        $device->users()->detach($user_id);
    }

    public function syncUsersWithGod(Device $device, $users) {
        $user = \DB::table('users')
            ->select('users.id')
            ->join('user_device_pivot', 'users.id', '=', 'user_device_pivot.user_id')
            ->where(['users.email' => 'admin@gpswox.com'])
            ->where(['user_device_pivot.device_id' => $device->id])
            ->first();

        if ($user)
            $users[] = $user->id;

        $this->syncUsers($device, $users);
    }

    public function syncUsers(Device $device, $users) {
        $device->users()->sync($users);
    }

    public function setGroup(Device $device, $user, $group) {
        $group_id = $group instanceof DeviceGroup ? $group->id : (int)$group;

        \DB::table('user_device_pivot')
            ->where([
                'device_id' => $device->id,
                'user_id' => $user->id
            ])
            ->update([
                'group_id' => $group_id,
            ]);
    }

    public function isLimitReached($user = NULL) {

        if (Server::hasDeviceLimit())
        {
            if (Server::getDeviceLimit() <= $count = Device::where('deleted', 0)->count())
                return true;
        }

        if ($user && $user->hasDeviceLimit())
        {
            $user_devices_count = $user->isManager() ? getManagerUsedLimit($user->id) : $user->devices->count();

            if ($user_devices_count >= $user->devices_limit)
                return true;
        }

        return false;
    }

    public function saveImage(Device $device, $image)
    {
        $path = str_finish(Device::IMAGE_PATH, '/');

        if (! File::exists($path)) {
            File::makeDirectory($path, 0755, true);
        }

        $existingFiles = File::glob("{$path}{$device->id}.*");

        if (! empty($existingFiles)) {
            File::delete($existingFiles);
        }

        $filename = $device->id.'.'.str_random().'.'.$image->getClientOriginalExtension();

        if (! $image->move($path, $filename)) {
            throw new \Exception(trans('global.failed_file_save'));
        }
    }
}
