<?php

namespace Drupal\restaurant\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\restaurant\App\Base;
use Drupal\restaurant\App\Misc;

use Symfony\Component\Yaml\Yaml;

abstract class AppForm extends FormBase implements Base
{

  /** Object Misc containing miscellaneos methods to share accross forms and Controllers
  */
  protected $service;

  /** Drupal database connection Object
  */
  protected $conn;

  public function __construct()
  {
    $this->service = new Misc();
    $this->conn = \Drupal::database();
  }

  /**
  * redirect HTTP response to url $path
  */
  /*final public function redirect($path)
  {
    return $this->service->redirect($path);
  } */

  /**
  * return the path to RestaurantHQ after the docroot
  */
  protected function getInstalledPath()
  {
    $file = str_replace($_SERVER['DOCUMENT_ROOT'], '', dirname(__FILE__));
    $parts = explode('modules', $file);
    return $parts[0] . 'modules' . DIRECTORY_SEPARATOR . 'RestaurantHQ' . DIRECTORY_SEPARATOR;
  }

  /**
  * Check if parameter exits
  * @param $name name of the parameter to check
  */
  final public function hasParam($name)
  {
    return $this->service->hasParam($name);
  }

  /**
  * shorthand for Drupal::routeMatch()->getParameter()
  */
  final public function getParam($name)
  {
    return $this->service->getParam($name);
  }

  final public function getDbConnection()
  {
    $this->db = new Db();
    return $this->db;
  }

  /**
  * add a drupal error message to the page
  * @param $message message to display
  * @param $type message type, defaults to "message"
  */
  public function addMessage($message, $type = 'message')
  {
    return $this->service->addMessage($message, $type);
  }

  /* Redirect to another url in the drupal sites
  */
  public function http_redirect($path)
  {
    $path = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . DIRECTORY_SEPARATOR . $path;
    header("Location: $path");
    exit;
  }

  /**
  * return true if admin page is in the path
  */
  public function inAdminPath()
  {
    return $this->service->inAdminPath();
  }

  /** return Drupal session Object
  */
  public function getSession()
  {
    return $this->service->getSession();
  }

  public function setSetting($name, $value)
  {
    return $this->service->setSetting($name, $value);
  }

  public function getSetting($name)
  {
    return $this->service->getSetting($name);
  }

  public function getEnvironment()
  {
    $file = file_get_contents(get_restaurant_path() . DIRECTORY_SEPARATOR . 'environment.yml');
    $value = Yaml::parse($file);
    return $value['environment'];
  }

}
