<?php

namespace App\Http\Controllers;

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

use App\Models\{Address,Domain,Zone};

class DomainController extends Controller
{
	// http://ftsc.org/docs/frl-1002.001
	public const NUMBER_MAX = 0x7fff;

	public function __construct()
	{
		$this->middleware('auth');
	}

	/**
	 * Add or edit a domain
	 */
	public function add_edit(Request $request,Domain $o)
	{
		if ($request->post()) {
			$this->authorize('admin',$o);

			$request->validate([
				// http://ftsc.org/docs/old/fsp-1028.002
				'name' => 'required|max:8|regex:/^[a-z-_~]{1,8}$/|unique:domains,name,'.($o->exists ? $o->id : 0),
				'dnsdomain' => 'nullable|regex:/^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){1,127}(?![0-9]*$)[a-z0-9-]+\.?)$/i|unique:domains,dnsdomain,'.($o->exists ? $o->id : NULL),
				'active' => 'required|boolean',
				'public' => 'required|boolean',
			]);

			foreach (['name','dnsdomain','active','public','homepage','notes'] as $key)
				$o->{$key} = $request->post($key);

			$o->save();

			return redirect()->action([self::class,'home']);
		}

		return view('domain.addedit')
			->with('o',$o);
	}

	/**
	 * Get all the hosts for a zone of a particular region (or not)
	 *
	 * @param Zone $o
	 * @param int $region
	 * @return Collection
	 */
	public function api_hosts(Zone $o,int $region): Collection
	{
		$oo = Address::where('role',Address::NODE_NC)
			->where('zone_id',$o->id)
			->when($region,function($query,$region) { return $query->where('region_id',$region); })
			->when((! $region),function($query) use ($region) { return $query->where('region_id',0); })
			->where('point_id',0)
			->FTNorder()
			->with(['system'])
			->get();

		return $oo->map(function($item) {
			return ['id'=>$item->host_id,'value'=>sprintf('%s %s',$item->ftn_3d,$item->system->name)];
		});
	}

	/**
	 * Find all the hubs for a host
	 *
	 * @param Zone $o
	 * @param int $host
	 * @return Collection
	 */
	public function api_hubs(Zone $o,int $host): Collection
	{
		$oo = Address::where('role',Address::NODE_HC)
			->where('zone_id',$o->id)
			->when($host,function($query,$host) { return $query->where('host_id',$host)->where('node_id','<>',0); })
			->with(['system'])
			->get();

		return $oo->map(function($item) {
			return ['id'=>$item->id,'value'=>sprintf('%s %s',$item->ftn_3d,$item->system->name)];
		});
	}

	/**
	 * Get all the regions for a zone
	 *
	 * @param Zone $o
	 * @return Collection
	 */
	public function api_regions(Zone $o): Collection
	{
		$oo = Address::where('role',Address::NODE_RC)
			->where('zone_id',$o->id)
			->where('node_id',0)
			->where('point_id',0)
			->orderBy('region_id')
			->with(['system'])
			->get();

		return $oo->map(function($item) {
			return ['id'=>$item->region_id,'value'=>sprintf('%s %s',$item->ftn_3d,$item->system->location)];
		});
	}

	public function home()
	{
		return view('domain.home');
	}
}