<?php

/**
 * FileIndexStatus
 *
 * @author Tomasz Świenty
 * @version 0.1
 * @copyright Copyright (c) eDokumenty
 */
final class FileIndexStatus extends Bean {


    public $pkeyName = 'fileid';
    public $tableName = 'files_index_status';


    private $saveCalled;


    public function __construct($db = NULL, $pkeyValue = NULL) {

        parent::__construct($db, $pkeyValue);

        if (!$this->isReferenced()) {
            $pkeyValue = $this->pkeyValue;
            $this->set('idxcnt', 0);
            $this->set('fileid', $pkeyValue);

            $this->pkeyName = 'a';
            parent::insert(FALSE);

            $this->pkeyName = 'fileid';
            $this->pkeyValue = $pkeyValue;
            $this->reload();
        }

    }


    public function setStatus($status, $is_err = TRUE) {

        $this->set('lasmsg', $status);
        $this->set('is_err', $is_err);

        $this->set('idxcnt', ($this->geti('idxcnt') + 1));

        $this->save();

    }


    /**
     * @param bool $reload
     * @return bool|int|string|void
     */
    public function update($reload = FALSE) {

        if (!$this->saveCalled) {
            trigger_error('Only save');
            return FALSE;
        }

        return parent::update($reload);

    }


    /**
     * @param bool $reload
     * @return bool|int|string|void
     */
    public function insert($reload = FALSE) {

        if (!$this->saveCalled) {
            trigger_error('Only save');
            return FALSE;
        }

        return parent::insert($reload);

    }


    /**
     * @param bool $reload
     * @return bool|int|string
     */
    public function save($reload = FALSE) {

        $this->saveCalled = TRUE;

        $this->set('idxdat', date('Y-m-d H:i:s'));

        if (!$this->isReferenced()) {
            $this->set('fileid', $this->pkeyValue);
            $this->set('idxcnt', 1);

            $this->pkeyName = 'a';
            $this->insert(FALSE);
            $this->pkeyName = 'fileid';
        }

        // jesli nie ma bledów zeruje licznik indeksacji
        if ($this->getb('is_err') === FALSE) {
            $this->set('idxcnt', 1);
        }

        $out = parent::save($reload);

        $this->saveCalled = FALSE;

        return $out;

    }

}