<?php

   namespace App\Http\Controllers;

   use Gate;
   use Carbon\Carbon;
   use App\Http\Requests;
   use App\Component;
   use App\Device;
   use Storage;
   use Excel;
   use GuzzleHttp\Client;
   use GuzzleHttp\Psr7\Request;
   use GuzzleHttp\Cookie\CookieJar;
   use App\Http\Controllers\Controller;
   use GuzzleHttp\Exception\ClientException;
   use GuzzleHttp\Exception\RequestException;
   use Illuminate\Http\Request as HttpRequest;

   class TrendLogController extends Controller
   {
      public function requestTrendLog() {
         if (Gate::denies('viewer')) {
            abort( 403, 'You cannot view trend logs.' );
         }
         $components = Component::where('xid', '>', 0)->get();
         $components = $components->each(function ($item) {
            $deviceName = Device::find($item->device_id)->display_name;
            $item['name'] = $deviceName . ' - ' . $item->details_name;
         });
         $components = $components->sortBy('name')->lists('name', 'id')->toArray();

         return view('trend_logs.request', compact('components'));
      }


      /**
       * @param HttpRequest $request
       *
       * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
       */
      public function viewTrendLog(HttpRequest $request) {
         if (Gate::denies('viewer')) {
            abort( 403, 'You cannot view trend logs.' );
         }
         $startDateTime = Carbon::parse($request['start'])->tz('America/Los_Angeles')->format('Y-m-d\TH:i:s.uP'); // 2016-02-10T00:00:00.000-10:00
         $endDateTime = Carbon::parse($request['end'])->tz('America/Los_Angeles')->format('Y-m-d\TH:i:s.uP');

         $component = Component::where('id', $request['component'])->first();
         $xid = $component->xid;
         $deviceComponentName = Device::where('id', $component->device_id)->first()->display_name . ' - ' . $component->details_name;

         $chartData = $this->getTrendLogJson($xid, $startDateTime, $endDateTime);

         $chartData = collect(json_decode($chartData, true));

         $request->flash();

         return view('trend_logs.view', compact('chartData', 'deviceComponentName'));
      }

      public function exportTrendLog(HttpRequest $request) {
         if (Gate::denies('viewer')) {
            abort( 403, 'You cannot view trend logs.' );
         }
         //		$chartData = Storage::get('test.json');
         $startDateTime = Carbon::parse( $request->old( 'start' ) )->format('Y-m-d\TH:i:s.uP');
         $endDateTime   = Carbon::parse( $request->old( 'end' ) )->format('Y-m-d\TH:i:s.uP');
         $component = Component::where('id', $request->old('component'))->first();
         $xid = $component->xid;
         //		$deviceComponentName = Device::where('id', $component->device_id)->first()->display_name . ' - ' . $component->details_name;
         $chartData = $this->getTrendLogJson( $xid, $startDateTime, $endDateTime );
         //		$chartData = Storage::get('test.json');
         $chartData = json_decode( $chartData, true );

         $plainStart = Carbon::parse( $request->old( 'start' ) );
         $plainEnd   = Carbon::parse( $request->old( 'end' ) );


         Excel::create( "$plainStart to $plainEnd TL", function ( $excel ) use ( $chartData ) {
            $excel->sheet( 'trend log', function ( $sheet ) use ( $chartData ) {
               $sheet->loadView( 'trend_logs.excel' )->with( 'chartData', $chartData );
               //				$sheet->with(json_decode($chartData, true));
            } );
         } )->download( 'xls' );
      }


      /**
       * Get Trend Log JSON
       *
       * @param $xid
       *
       * @param $startDateTime
       * @param $endDateTime
       *
       * @return array|\Psr\Http\Message\StreamInterface
       * @internal param $value
       */

      public function getTrendLogJson($xid, $startDateTime, $endDateTime) {
         if (Gate::denies('viewer')) {
            abort(403, 'You cannot view trend logs.');
         }
         if ($xid == '') {
            abort(403, 'You must declare an XID.');
         }
         $this->login();
         $jar     = session()->get( 'cookieJar' );
         if($jar) {
            $client  = new Client( [ 'base_uri' => 'http://' . env('MANGO_IP') . '/rest/v1/', 'cookies' => $jar ] );
            $headers = [
               'Accept'          => 'application/json',
               'Accept-Encoding' => 'gzip, deflate, sdch',
               'Accept-Language' => 'en-US,en;q=0.8',
               'Cache-Control'   => 'no-cache',
               'Content-Type'    => 'application/json',
               'Connection'      => 'keep-alive',
            ];

            try {
               $response = $client->request( 'GET', "point-values/" .
                                                  $xid .
                                                  '?useRendered=false' .
                                                  '&unitConversion=false' .
                                                  '&from=' .
                                                  $startDateTime . // 2016-02-10T00:00:00.000-10:00
                                                  '&to=' .
                                                  $endDateTime . // 2016-02-11T23:59:59.999-10:00
                                                  '&rollup=NONE&timePeriodType=MINUTES&timePeriods=15'
                  , [
                                                'headers' => $headers,
                                                //					'body'    => $json,
                                             ] );
               return $response->getBody();
            } catch( RequestException $e ) {
               $jsonResponse[] = $e->getRequest()->getHeaders();
               if ( $e->hasResponse() ) {
                  $jsonResponse[] = $e->getResponse()->getHeaders();
               }

               return json_encode( $jsonResponse );
            } catch( ClientException $e ) {
               $jsonResponse[] = $e->getRequest()->getHeaders();
               if ( $e->hasResponse() ) {
                  $jsonResponse[] = $e->getResponse()->getHeaders();
               }

               return json_encode( $jsonResponse );
            }
         } else {
            return 'Try logging in again.';
         }

      }

      public function login() {
         $headers = [
            'Accept'   => 'application/json',
            'Password' => env('MANGO_PW'),
         ];
         $jar     = new CookieJar;
         $client  = new Client( [ 'base_uri' => 'http://' . env('MANGO_IP') . '/rest/v1/', 'cookies' => $jar ] );

         session()->put( 'cookieJar', $jar );
         $client->get( 'login/' . env('MANGO_USER'), [ 'headers' => $headers ] );
      }


   }