<?php
namespace nur\sery\file\csv;

use nur\sery\cl;
use nur\sery\ref\file\csv\ref_csv;
use nur\sery\str;

class csv_flavours {
  const MAP = [
    "oo" => ref_csv::OO_FLAVOUR,
    "ooffice" => ref_csv::OO_FLAVOUR,
    ref_csv::OOCALC => ref_csv::OO_FLAVOUR,
    "xl" => ref_csv::XL_FLAVOUR,
    "excel" => ref_csv::XL_FLAVOUR,
    ref_csv::MSEXCEL => ref_csv::XL_FLAVOUR,
    "dumb;" => ref_csv::DUMB_XL_FLAVOUR,
    "dumb," => ref_csv::DUMB_OO_FLAVOUR,
    "dumb" => ref_csv::DUMB_FLAVOUR,
  ];
  
  const ENCODINGS = [
    ref_csv::OO_FLAVOUR => ref_csv::OO_ENCODING,
    ref_csv::XL_FLAVOUR => ref_csv::XL_ENCODING,
    ref_csv::DUMB_FLAVOUR => ref_csv::DUMB_ENCODING,
  ];
  
  static final function verifix(?string $flavour): ?string {
    if ($flavour === null) return null;
    $lflavour = strtolower($flavour);
    if (array_key_exists($lflavour, self::MAP)) {
      $flavour = self::MAP[$lflavour];
    }
    if (strlen($flavour) < 1) $flavour .= ",";
    if (strlen($flavour) < 2) $flavour .= "\"";
    if (strlen($flavour) < 3) $flavour .= "\\";
    return $flavour;
  }

  static final function get_name(string $flavour): string {
    if ($flavour == ref_csv::OO_FLAVOUR) return ref_csv::OOCALC;
    elseif ($flavour == ref_csv::XL_FLAVOUR) return ref_csv::MSEXCEL;
    else return $flavour;
  }
  
  static final function get_params(string $flavour): array {
    return [$flavour[0], $flavour[1], $flavour[2]];
  }

  static final function get_encoding(string $flavour): ?string {
    return cl::get(self::ENCODINGS, $flavour);
  }

  static final function is_dumb(string $flavour, ?string &$sep): bool {
    if (!str::del_prefix($flavour, "xxx")) return false;
    $sep = $flavour;
    if (!$sep) $sep = ";";
    return true;
  }
}
