<?php

namespace App\Http\Traits\SoftwareLicense;

use Illuminate\Support\Facades\Auth;
use App\Models\SoftwareLicense\SoftwareLicenseManufacturer;
use App\User;
use Carbon\Carbon;

trait SoftwareAssetTrait
{
    

    /**
     * set up  history record for user action on a software asset
     * 
     * @param string action
     * @param object $assetDetails
     * @param array $userIds 
     * 
     * @return array
     */
    public function setSoftwareUserHistoryData($action, $assetDetails, $userIds) 
    {
        $historyData = [];

        foreach ($userIds  as $userId) 
        {
            $user = $this->getUserForLicenseMemeber('id', $userId);
            $description = $this->getDescriptionForSoftwareUserActions($action, $user, $assetDetails);
            $historyData[] = [
                'software_license_id'       => $assetDetails->id,
                'action'                    => $action,
                'description'               => $description,
                'license_user_id'           => $userId,
                'software_license_key_id'   => '',
                'user_id'                   => Auth::id(),
                'created_at'                => Carbon::now(),
                'updated_at'                => Carbon::now()
            ];
        }

        return $historyData;
    }

    /**
     *Create description for user action
     * 
     * @param action The action that was performed.
     * @param data The data object that was passed to the event.
     * 
     * @return The return value is a string.
     */
    public function getDescriptionForSoftwareUserActions($action, $user, $assetDetails)
    {             
        $userName = $user->first_name ? $user->user_name : $user->email;
        $userId   = $user->id;        
        $actionType = ($action === 'user_added') ? 'license-history.UserAdded' : 'license-history.UserRemoved';

        return  __($actionType, [
            'userName' => $userName,
            'userId'   => $userId,
            'assetId' => $assetDetails->id,
            'asset'    => $assetDetails->name,
            'key'      => ''
        ]);
    }

    /**
     * create an array of software asset user data based on Software asset details and member data.
     * 
     * @param $assetDetails
     * @param $softwareAssetMemberData
     *  
     * @return Array 
    */
    public function getSoftwareAssetUserData($assetDetails, $softwareAssetMemberData)
    {
        return [
            'software_license_id'       => $assetDetails->id,
            'user_id'                   => $softwareAssetMemberData->user_id,
            'software_license_key_id'   => 0,
            'status'                    => $softwareAssetMemberData->status,
            'joined_on'                 => $softwareAssetMemberData->joined_on
        ];
    }

     /**
     * The function returns an array with initial values to create license asset
     * 
     * @param string $name
     * 
     * @return array
    */
    public function formatAssetDataForCreateWithIntegration($name)
    {
        $manufacture = $this->getManufacturer($name);

        return [
            'name'                              => $name,
            'software_license_manufacturer_id'  => $manufacture->id,
            'license_key_type'                  => 'user_license',
            'key_usage_type'                    => 'n/a',
            'type'                              => 'saas_cloud',
            'license_type'                      => 'subscription' 
        ];        
    }

    /**
     * get manufacture for the license asset
     *  
     * @param string $name
     * 
     * @return object
     */
    public function getManufacturer($name)
    {
        return SoftwareLicenseManufacturer::firstOrCreate(['name' => $name]);
    }

    /**
     * get user for License Memeber with email
     * 
     * @param strinng $key
     * @param mixed $value
     * 
     * @return mixed 
     */
    public function getUserForLicenseMemeber($key, $value)
    {
        return User::where($key, $value)->first();
    }

    /**
     * Set imported software asset history for update with integration
     * 
     * @param object $oldData
     * @param array $data
     * 
     * @return array 
     */
    public function setImportedAssetHistoryForUpdateWithIntegration($oldData, $data)
    {
        $changedData = [];
        $historyData = [];
        $historyData['software_license_id'] = $data['id'];
        $historyData['action'] = 'updated';

        foreach ($data as $key => $value) {
            
            if (($value || $value == 0) || (isset($oldData->key) && $oldData->key)) {
                
                if ($value != $oldData->getRawOriginal($key)) {
                    $changedData[$key] = [
                        'old' => $oldData->getRawOriginal($key),
                        'new' => $value
                    ];

                    $historyData['old_' . $key] = $oldData->getRawOriginal($key);
                    $historyData['new_' . $key] = $value;
                }
            }
        }

        $description = $this->getStatusDescriptionForEdited($oldData,$changedData);
        $historyData['description'] = $description;
        $historyData['user_id'] = Auth::id();
        $historyData['created_at'] = Carbon::now();
        $historyData['updated_at'] = Carbon::now();

        return $historyData;
    }

    /**
     * Set imported software asset history for create with integration
     * 
     * @param object $asset
     * 
     * @return array
     */
    public function setImportedAssetHistoryForCreateWithIntegration($asset)
    {
        $description = $this->getStatusDescriptionForCreated($asset);
        
        return [
            'software_license_id'   => $asset->id,
            'action'                => 'created',
            'description'           => $description,
            'user_id'               => Auth::id(),
            'created_at'            => Carbon::now(),
            'updated_at'            => Carbon::now(),
        ];
          
    }

    /**
     * get status description for created
     * 
     * @param object $asset
     * 
     * @return string
     */
    public function getStatusDescriptionForCreated($asset)
    {
        $name = $asset->name;
        $assetId = $asset->id;
        
        return  __('license-history.Created', [
            'name' => $name,
            'assetId' => $assetId
        ]);
    }

    /**
     * get status description for edited
     * 
     * @param array $changedData
     * @param  $asset
     * 
     * @return string
     */
    public function getStatusDescriptionForEdited($asset,$changedData)
    {
        $comments = '';
        
        foreach ($changedData as $key => $data) {
           
            if ($key == 'status') {
                $data['old'] = config('software-license.licence_status')[$data['old']] ?? '';
                $data['new'] = config('software-license.licence_status')[$data['new']] ?? '';
            }
            $comments .=  str_replace("_", " ", $key) . " changed " . ($data['old'] ? ("from " . $data['old']) : '') . " to " . $data['new'];
        }

        return  __('license-history.Updated', [
            'comments' => $comments,
            'name' => $asset->name,
            'assetId' => $asset->id
        ]);
    }
}