<?php

namespace App\Http\Controllers\Simulator;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Validator;

class ArtistSimulatorOverviewController extends Controller
{
    /**
     * GenderLookupOverviewController constructor.
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $pageLength = Auth::user()->table_page_length;

        $testDataArtists = array();
        $testDataMediums = array();
        $statusMessage = '';
        $statusMessageArtist = '';
        $statusMessageMedium = '';

        return view('simulator.artist-simulator-overview', ['pageLength'=>$pageLength, 'testDataArtists'=>$testDataArtists, 'testDataMediums'=>$testDataMediums, 'statusMessage'=>$statusMessage, 'statusMessageArtist'=>$statusMessageArtist, 'statusMessageMedium'=>$statusMessageMedium]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function simulate(Request $request)
    {
        $pageLength = Auth::user()->table_page_length;

        // validate form
        $validator = Validator::make($request->all(), [
            'bornDate'      => '',
            'diedDate'      => '',
            'firstname'     => '',
            'lastname'      => '',
            'objectDate'    => '',
            'objectMedium'  => '',
            'sourceType'    => '',
        ], [
            'firstname.required' => 'Bitte geben Sie den Vornamen DE ein',
            'lastname.required' => 'Bitte geben Sie den Nachnamen DE ein',
            'bornDate.required' => 'Bitte geben Sie das Geburtsdateum ein',
            'diedDate.required' => 'Bitte geben Sie das Sterbedatum ein',
            'objectDate.required' => 'Bitte geben Sie den Objektdatum ein',
            'objectMedium.required' => 'Bitte geben Sie den Medium ein',
            'sourceType.required' => 'Bitte geben Sie das Kunsthaus ein',
        ]);

        // if validation fails
        if ($validator->fails()) {

            return redirect(URL::previous())
                ->withErrors($validator->errors(), 'formErrors')
                ->withInput($request->input());

        } else {

            // get test data form service
            $testData = $this->getTestDataFromService($request);

            // get artist list from response
            $artistList = array();
            $mediumList = array();
            $statusMessage = '';
            $statusMessageArtist = '';
            $statusMessageMedium = '';

            if(!is_null($testData)) {
                $artistList = $testData->tartists;
                $mediumList = $testData->tmediumList;
                $statusMessage = $testData->statusMessage;
                $statusMessageArtist = $testData->statusMessageArtist;
                $statusMessageMedium = $testData->statusMessageMedium;
            }



            // get entired artist data from database
            $testDataArtists = DB::table('t_artist')
                ->select(
                    'id',
                    'status',
                    'gender_id',
                    'firstname_de',
                    'firstname_en',
                    'firstname_fr',
                    'lastname_de',
                    'lastname_en',
                    'lastname_fr',
                    'born_date',
                    'born_location_de',
                    'born_location_en',
                    'born_location_fr',
                    'died_date',
                    'died_location_de',
                    'died_location_en',
                    'died_location_fr',
                    'editor',
                    'lastchange'
                )
                ->whereIn('id', $artistList)
                ->get();

            // get entired artist data from database
            $testDataMediums = DB::table('t_medium')
                ->leftJoin('t_medium_category', 't_medium.t_medium_category_id', '=', 't_medium_category.id')
                ->select(
                    't_medium.id',
                    't_medium.searchword_de',
                    't_medium.searchword_en',
                    't_medium.searchword_fr',
                    't_medium_category.name'
                )
                ->whereIn('t_medium.id', $mediumList)
                ->get();

            return view('simulator.artist-simulator-overview', ['pageLength'=>$pageLength, 'testDataArtists'=>$testDataArtists, 'testDataMediums'=>$testDataMediums, 'statusMessage'=>$statusMessage, 'statusMessageArtist'=>$statusMessageArtist, 'statusMessageMedium'=>$statusMessageMedium]);
        }




    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * @param $request
     * @return \Illuminate\Http\RedirectResponse
     */
    private function getTestDataFromService($request) {

        // push form request data to array
        $data = array(
            "bornDate" => $request->bornDate,
            "diedDate" => $request->diedDate,
            "firstname" => $request->firstname,
            "lastname" => $request->lastname,
            "objectDate" => $request->objectDate,
            "objectMedium" => $request->objectMedium,
            "sourceType" => $request->sourceType
        );

        $jsonData = json_encode($data);

        // call rest service
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => env('SERVICE_URL_STARTTESTMACHINE',null),
            CURLOPT_USERPWD => "admin:admin",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30000,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $jsonData,
            CURLOPT_HTTPHEADER => array(
                "accept: */*",
                "accept-language: en-US,en;q=0.8",
                "content-type: application/json",
            ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);
        $info = curl_getinfo($curl);
        $httpStatusCode = $info['http_code'];

        curl_close($curl);

        $response = json_decode($response);

        if ($err) {
            echo "cURL Error #:" . $err;
        } else {
            //dd(json_decode($response));

            if ($httpStatusCode == 500) {
                return null;
            } else {
                return $response;
            }
        }
    }

}
