#!/usr/bin/env php
<?php

use app\Admin;
use app\CliUtil;
use app\foreignone\files\ArchiveType;
use app\foreignone\Page;
use app\foreignone\Post;
use app\foreignone\Upload;

require_once __DIR__.'/../src/init.php';

new CliUtil()

->on('admin-add', function() {
    list($login, $password) = _get_admin_login_password_input();

    if (Admin::exists($login))
        CliUtil::die("Admin ".$login." already exists");

    $id = Admin::add($login, $password);
    echo "ok: id = $id\n";
})

->on('admin-delete', function() {
    $login = CliUtil::input('Login: ');
    if (!Admin::exists($login))
        CliUtil::die("No such admin");
    if (!Admin::delete($login))
        CliUtil::die("Database error");
    echo "ok\n";
})

->on('admin-set-password', function() {
    list($login, $password) = _get_admin_login_password_input();
    echo Admin::setPassword($login, $password) ? 'ok' : 'fail';
    echo "\n";
})

->on('blog-erase', function() {
    $db = getDB();
    $tables = ['posts', 'posts_texts'];
    foreach ($tables as $t) {
        $db->query("TRUNCATE TABLE $t");
    }
})

->on('posts-html', function() {
    $kw = ['include_hidden' => true];
    $posts = Post::getList(0, Post::getCount(...$kw), ...$kw);
    foreach ($posts as $p) {
        $texts = $p->getTexts();
        foreach ($texts as $t) {
            $t->updateHtml();
            $t->updateText();
        }
    }
})

->on('posts-images', function() {
    $kw = ['include_hidden' => true];
    $posts = Post::getList(0, Post::getCount(...$kw), ...$kw);
    foreach ($posts as $p) {
        $texts = $p->getTexts();
        foreach ($texts as $t) {
            $t->updateImagePreviews(true);
        }
    }
})

->on('pages-html', function() {
    $pages = Page::getAll();
    foreach ($pages as $p) {
        $p->updateHtml();
    }
})

->on('add-files-to-uploads', function() {
    $path = CliUtil::input('Enter path: ');
    if (!file_exists($path))
        CliUtil::die("file $path doesn't exists");
    $name = basename($path);
    $ext = extension($name);
    $id = Upload::add($path, $name, '');
    echo "upload id: $id\n";
})

->on('archive-reindex', function() {
    $archives = array_map(fn($c) => $c->value, ArchiveType::cases());
    $s = CliUtil::input('Enter archive to reindex (variants: '.implode(', ', $archives).': ');
    $c = ArchiveType::from($s);
    $f = "{$s}_reindex";
    echo "calling $f()... ";
    call_user_func($f);
    echo "done\n";
})

->run();

function _get_admin_login_password_input(): array {
    $login = CliUtil::input('Login: ');
    $pwd1 = CliUtil::silentInput("Password: ");
    $pwd2 = CliUtil::silentInput("Again: ");

    if ($pwd1 != $pwd2)
        CliUtil::die("Passwords do not match");

    if (trim($pwd1) == '')
        CliUtil::die("Password can not be empty");

    if (strlen($login) > Admin::ADMIN_LOGIN_MAX_LENGTH)
        CliUtil::die("Login is longer than max length (".Admin::ADMIN_LOGIN_MAX_LENGTH.")");

    return [$login, $pwd1];
}
