<?php

namespace App\Services\DiscoveryTools\Kandji;

use App\User;
use App\Models\Asset;
use App\Models\TechnicalSpecs;
use App\Repositories\DiscoveryTools\KandjiRepository;

class KandjiSyncService
{
    public function __construct(protected KandjiRepository $repository)
    {
    }

    /**
     * Parse the Kandji response and create an arrray for insert into DB
     *
     * @param $response  MobileIron api response
     *
     * @return Array
     */
    public function parseKandjiApiResponse($response, $details)
    {
        if ($response) {
            $data['user_name']      = isset($response['general']['assigned_user']['name']) ? $response['general']['assigned_user']['name'] : '';
            $data['email']          = isset($response['general']['assigned_user']['email']) ? $response['general']['assigned_user']['email'] : '';
            $data['serial_no']      = isset($response['hardware_overview']['serial_number']) ? $response['hardware_overview']['serial_number'] : '';

            $assetId                = $this->getAssetId($data['serial_no']);
            $userId                 = $this->getUserId($data['email']);

            $data['asset_id']       = $assetId;
            $data['user_id']        = $userId;
            $data['asset_tag']      = $response['general']['asset_tag'] ?? null;
            $data['device_id']      = $response['general']['device_id'] ?? '';
            $data['device_name']    = $response['general']['device_name'] ?? '';
            $data['model']          = $response['general']['model'] ?? '';
            $data['platform']       = $response['general']['platform'] ?? null;
            $data['os_version']     = $response['general']['os_version'] ?? null;
            $data['processor_speed'] = $this->getProcessorSpeed($response);
            $data['ram']            = $this->getRamValue($response);
            $data['disk_capacity']  = $this->getDiscCapacity($response);
            $data['os']             = $this->getOperatingSystem($response);
            $data['activation_lock'] = $this->getActivationLock($response);
            $data['last_checkin']   = format_kandji_check_in_date($details['last_check_in']);
            $data['first_enrollment'] = format_kandji_date($response['general']['first_enrollment']);
            $data['last_enrollment'] = format_kandji_date($response['general']['last_enrollment']);

            return $data;
        }

        return false;
    }

    /**
     * get the Asset id from serial #
     *
     * @param string $serial
     * @return int
     */
    public function getAssetId($serial)
    {
        if ($serial) {
            $asset = Asset::select('id')->where('serial_no', $serial)->first();

            return $asset ? $asset->id : 0;
        }

        return 0;
    }

    /**
     * get the user id from email.
     *
     * @param string $email
     *
     * @return int
     */
    public function getUserId($email)
    {
        if ($email) {
            $user = User::select('id')->where('email', $email)->first();

            return $user ? $user->id : 0;
        }

        return 0;
    }


    /**
     * Create Technical Spec
     *
     * @param $data  Kandji Response Data
     * @param $makeAndModelId  Make and Model ID
     */
    public function createTechSpec($data, $makeAndModelId)
    {
        if (!$data['processor_speed'] || !$data['ram'] || !$data['disk_capacity'] || !$makeAndModelId) {
            return null;
        }

        $techSpec = ($data['processor_speed'] ?: 'Ghz') . '/' . ($data['ram'] ?: 'GB') . '/' . ($data['disk_capacity'] ?: 'GB');
        $technicalSpecs = TechnicalSpecs::firstOrCreate([
            'details'  => $techSpec,
            'make_and_model_id' => $makeAndModelId
        ], [
            'original_value' => 0,
            'original_value' => 0,
            'auto_created' => 1,
        ]);
        return $technicalSpecs;
    }

    /**
     * Return the processor speed from the Kandji response
     * 
     * @param array $kandjiResponse
     * @return string
     */
    public function getProcessorSpeed($kandjiResponse)
    {
        return isset($kandjiResponse['hardware_overview']['processor_speed']) ?
            $kandjiResponse['hardware_overview']['processor_speed'] : null;
    }

    /**
     * Return the Operating system value from Kandji Response
     * 
     * @param array $kandjiResponse
     * @return string
     */
    public function getOperatingSystem($kandjiResponse)
    {
        return isset($kandjiResponse['apple_business_manager']['os']) ?
            $kandjiResponse['apple_business_manager']['os'] : null;
    }

    /**
     * Return the Activation Lock value from Kandji Response
     * 
     * @param array $kandjiResponse
     * @return string
     */
    public function getActivationLock($kandjiResponse)
    {
        return isset($kandjiResponse['activation_lock']['user_activation_lock_enabled']) ?
            $kandjiResponse['activation_lock']['user_activation_lock_enabled'] : false;
    }

    /**
     * Taking the RAM memory from the kandji response
     *
     * @param array $kandjiResponse
     */
    public function getRamValue($kandjiResponse)
    {
        $ramDetails = isset($kandjiResponse['hardware_overview']['memory']) ?
            $kandjiResponse['hardware_overview']['memory'] : null;

        //$ramDetails string should be like this  "8 GB 2133 MHz LPDDR3"
        //So we need to extract 8 GB

        if ($ramDetails) {
            $explode = explode('GB', $ramDetails);
            if (isset($explode[0])) {
                return trim($explode[0]) . 'GB';
            }
        }

        return null;
    }

    /**
     * Taking The Disc Capacity values from Kanji Response
     * 
     * @param array $kandjiResponse
     */
    public function getDiscCapacity($kandjiResponse)
    {
        $discVolumes = $kandjiResponse['volumes'];
        if (!$discVolumes) {
            return null;
        }

        $discVolumeSum = 0;
        foreach ($kandjiResponse['volumes'] as $volume) {
            // Select volumes with format APFS to sum
            if ($volume['format'] == "APFS" && $volume['name'] == "Macintosh HD") {
                $discVolumeSum += (int)trim(current(explode('GB', $volume['capacity'])));
            }
        }

        return getStandardHDDCapacity($discVolumeSum);
    }
}
