<?php
namespace App\Models;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;

class Issue{

  public static function getCollection($status = []){
    $redmineUser = session('redmine_user');
    $collection = new Collection();

    // Issue assegnati direttamente all'utente
    $issueResponse = Http::get(session('azienda')->redmine_url.'/issues.json', [
      'key' => $redmineUser->api_key,
      'assigned_to_id' => $redmineUser->id,
      'status_id' => ($status!=null && count($status)>0)?implode('|', $status):'open',
      'limit' => 100,
    ]);

    // dd($response->object()->issues);
    try{
      foreach($issueResponse->object()->issues as $issue){
        $collection->push($issue);
      }
    }catch(\Exception $e){
    }

    // Issue assegnati ai gruppi di cui l'utente fa parte
    $groupResponse = Http::get(session('azienda')->redmine_url.'/users/current.json', [
      'key' => $redmineUser->api_key,
      'include' => 'groups'
    ]);
    // dd($groupResponse->object()->user->groups);

    try{
      foreach($groupResponse->object()->user->groups as $group){
        $issueResponse = Http::get(session('azienda')->redmine_url.'/issues.json', [
          'key' => $redmineUser->api_key,
          'assigned_to_id' => $group->id,
          'status_id' => ($status!=null && count($status)>0)?implode('|', $status):'open',
          'limit' => 100,
        ]);

        foreach($issueResponse->object()->issues as $issue){
          $collection->push($issue);
        }
      }
    }catch(\Exception $e){
    }

    return $collection;
  }

  public static function getStati(){
    $redmineUser = session('redmine_user');

    // issueStatus
    $response = Http::get(session('azienda')->redmine_url.'/issue_statuses.json', [
      'key' => $redmineUser->api_key,
    ]);

    $issueStatus = array();
    foreach($response->object()->issue_statuses as $issue_status){
      $issueStatus[$issue_status->id] = $issue_status->name;
    }

    return $issueStatus;
  }

  public static function getAttivita(){
    $redmineUser = session('redmine_user');

    // Activity
    $response = Http::get(session('azienda')->redmine_url.'/enumerations/time_entry_activities.json', [
      'key' => $redmineUser->api_key,
    ]);

    $attivita = array();
    foreach($response->object()->time_entry_activities as $time_entry_activities){
      if(!$time_entry_activities->active) continue;
      $attivita[$time_entry_activities->id] = $time_entry_activities->name;
    }

    return $attivita;
  }

}
