<?php

class Image implements JsonSerializable {
    private $id = 0;
    private $album_id = 0;
    private $albumfolder = "";
    private $filename = "";
    private $title = "";
    private $description = "";
    private $createtime = "";

    const VALID_MIME_TYPES = array(
        "image/jpeg",
        "image/png",
        "image/gif"
    );

    const MIME_TYPES_EXT = array(
        "image/jpeg" => ".jpg",
        "image/jpeg" => ".jpeg",
        "image/png" => ".png",
        "image/gif" => ".gif"
    );

    const EXT_MIME_TYPES = array(
        "jpg" => "image/jpeg",
        "jpeg" => "image/jpeg",
        "png" => "image/png",
        "gif" => "image/gif"
    );

    public function getID() {
        return intval($this->id);
    }

    public function getAlbumID() {
        return intval($this->album_id);
    }

    public function getCreateTime($flag = 0) {
        switch ($flag) {
           case TIMESTAMP:
              return strtotime($this->createtime);
              break;
           case PRETTY:
              return date("F j Y H:i:s", strtotime($this->createtime));
              break;
           default:
              return $this->createtime;
              break;
        }
    }

    public function getFileName($flag = 0) {
        switch ($flag) {
           case HTMLSAFE:
              return htmlspecialchars($this->filename);
              break;
           case HTMLFORMSAFE:
              return htmlspecialchars($this->filename, ENT_QUOTES);
              break;
           case CSVSAFE:
              return str_replace('"', '""', $this->filename);
              break;
           default:
              return $this->filename;
              break;
        }
    }

    public function getThumbnail($flag = 0) {
        switch ($flag) {
            case HTMLSAFE:
                return htmlspecialchars($this->filename);
                break;
            case HTMLFORMSAFE:
                return htmlspecialchars($this->filename, ENT_QUOTES);
                break;
            case CSVSAFE:
                return str_replace('"', '""', $this->filename);
                break;
            case URLSAFE:
                return htmlspecialchars(basename(THUMBNAILFOLDER) . "/" . $this->albumfolder . $this->filename, ENT_QUOTES);
                break;
            default:
                return $this->filename;
                break;
        }
    }

    public function getAlbumFolder($flag = 0) {
        switch ($flag) {
           case HTMLSAFE:
              return htmlspecialchars($this->albumfolder);
              break;
           case HTMLFORMSAFE:
              return htmlspecialchars($this->albumfolder, ENT_QUOTES);
              break;
           case CSVSAFE:
              return str_replace('"', '""', $this->albumfolder);
              break;
           default:
              return $this->albumfolder;
              break;
        }
    }

    public function getTitle($flag = 0) {
        switch ($flag) {
           case HTMLSAFE:
              return htmlspecialchars($this->title);
              break;
           case HTMLFORMSAFE:
              return htmlspecialchars($this->title, ENT_QUOTES);
              break;
           case CSVSAFE:
              return str_replace('"', '""', $this->title);
              break;
           default:
              return $this->title;
              break;
        }
    }

    public function getDescription($flag = 0) {
        switch ($flag) {
           case HTMLSAFE:
              return htmlspecialchars($this->description);
              break;
           case HTMLFORMSAFE:
              return htmlspecialchars($this->description, ENT_QUOTES);
              break;
           case CSVSAFE:
              return str_replace('"', '""', $this->description);
              break;
           default:
              return $this->description;
              break;
        }
    }

    public function getPathToFile() {
        return (dirname($_SERVER['SCRIPT_FILENAME']) . "/" . ALBUMFOLDER . $this->getFileName());
    }

    public function getURLToFile() {
        return (ALBUMFOLDER . $this->getFilePath() . $this->getFileName());
    }

    public function setID($id = null) {
        if (is_null($id)) return false;
        $id = abs(intval($id));
        if ($id == 0) return false;
        $this->id = $id;
        return true;
    }

    public function setAlbumID($id = null) {
        if (is_null($id)) return false;
        $id = intval($id);
        if ($id <= 0) return false;
        $this->album_id = $id;
        return true;
    }

    public function setAlbumFolder($folder = null) {
        if ( is_null($folder) || ($folder == "") ) return false;
        $this->albumfolder = $folder;
    }

    public function setFileName($name = null) {
        if ( is_null($name) || ($name == "") ) return false;
        $this->filename = $name;
    }

    public function setTitle($title = null) {
        if ( is_null($title) || ($title == "") ) return false;
        $this->title = $title;
    }

    public function setDescription($description = null) {
        if ( is_null($description) || ($description == "") ) return false;
        $this->description = $description;
    }

    public static function getImagesForAlbum($albumid = 0) {
        global $globaldbh;

        $query = "SELECT id FROM " . AppDB::TABLE_IMAGES . " WHERE album_id=:album_id ORDER BY filename";
        $sth = $globaldbh->prepare($query);
        $sth->bindValue(":album_id", (int) $albumid, PDO::PARAM_INT);
        $sth->execute();
        $thelist = array();
        while ( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
            $thelist[] = new Image($row['id']);
        }
        return $thelist;
    }

    public function createThumbnail() {
        if ( $this->getAlbumID() == 0 ) return false;

        $albumimage = ALBUMFOLDER . $this->getAlbumFolder() . $this->getFileName();
        $thumbnailimage = THUMBNAILFOLDER . $this->getAlbumFolder() . $this->getFileName();
        $ext = substr($albumimage, strrpos($albumimage, ".") + 1);
        // Resize image
        list($width, $height) = getimagesize($albumimage);
        $ratio = $width/$height;
        $maxW = 284;
        $maxH = 160;
        $newWidth = $maxW;
        $newHeight = ($maxW/$width) * $height;
        if ( $newHeight > $maxH ) {
            $newHeight = $maxH;
            $newWidth = ($maxH/$height) * $width;
        }
        if ( file_exists($thumbnailimage) ) unlink($thumbnailimage);
        $newimg = imagecreatetruecolor($newWidth, $newHeight);
        switch ( Image::EXT_MIME_TYPES[strtolower($ext)] ) {
            case "image/jpeg":
                $image = imagecreatefromjpeg($albumimage);
                imagecopyresampled($newimg, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
                $success = imagejpeg($newimg, $thumbnailimage);
                break;
            case "image/png":
                $image = imagecreatefrompng($albumimage);
                imagecopyresampled($newimg, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
                imagepng($newimg, $thumbnailimage);
                break;
            case "image/gif":
                $image = imagecreatefromgif($albumimage);
                imagecopyresampled($newimg, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
                imagegif($newimg, $thumbnailimage);
                break;
        }
    }

    public static function getList() {
        global $globaldbh;

        $query = "SELECT id FROM " . AppDB::TABLE_IMAGES . " ORDER BY album_id, filename";
        $sth = $globaldbh->prepare($query);
        $sth->execute();
        $thelist = array();
        while ( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
            $thelist[] = new Image($row['id']);
        }
        return $thelist;
    }

    public function jsonSerialize() {
        return [
            'id' => $this->getID(),
            'album_id' => $this->getAlbumID(),
            'albumfolder' => $this->getAlbumFolder(),
            'imageurl' => basename(ALBUMFOLDER) . "/" . $this->getAlbumFolder() . $this->getFileName(),
            'thumburl' => basename(THUMBNAILFOLDER) . "/" . $this->getAlbumFolder() . $this->getFileName(),
            'title' => $this->getTitle(),
            'description' => $this->getDescription(),
            'createtime' => $this->getCreateTime()
        ];
    }

    public function delete() {
        global $globaldbh;

        $query = "DELETE FROM " . AppDB::TABLE_IMAGES . " WHERE id=:id";
        $sth = $globaldbh->prepare($query);
        $sth->bindValue(":id", (int) $this->getID(), PDO::PARAM_INT);
        $sth->execute();
        $this->setID(0);
        $thumbnailfile = THUMBNAILFOLDER . $this->getAlbumFolder() . $this->getFileName();
        if ( file_exists($thumbnailfile) ) unlink($thumbnailfile);
    }

    public function save() {
        global $globaldbh;

        $query = "INSERT INTO " . AppDB::TABLE_IMAGES . " ";
        $query .= "(id, album_id, filename, title, description, createtime) ";
        $query .= "VALUES(:id, :album_id, :filename, :title, :description, NOW()) ";
        $query .= "ON DUPLICATE KEY UPDATE ";
        $query .= "album_id=:album_id, filename=:filename, title=:title, description=:description";
        $sth = $globaldbh->prepare($query);
        $sth->bindValue(":id", (int) $this->getID(), PDO::PARAM_INT);
        $sth->bindValue(":album_id", (int) $this->getAlbumID(), PDO::PARAM_INT);
        $sth->bindValue(":filename", $this->getFileName(), PDO::PARAM_STR);
        $sth->bindValue(":title", $this->getTitle(), PDO::PARAM_STR);
        $sth->bindValue(":description", $this->getDescription(), PDO::PARAM_STR);
        $sth->execute();
        //print_r($this);
        //print_r($sth->errorInfo());
        if ( $this->getID() == 0 ) {
            $this->setID($globaldbh->lastInsertId());
            $this->createThumbnail();
        }
    }

    function __construct($reqid = 0) {
        global $globaldbh;
        
        $reqid = intval($reqid);
        $query = "SELECT i.id, i.album_id, i.filename, i.title, i.description, i.createtime, a.foldername ";
        $query .= "FROM " . AppDB::TABLE_IMAGES . " AS i LEFT JOIN " . AppDB::TABLE_ALBUMS . " as a ON i.album_id=a.id WHERE i.id=:id";
        $sth = $globaldbh->prepare($query);
        $sth->bindValue(":id", $reqid, PDO::PARAM_INT);
        $sth->execute();
        if ( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
            $this->setID($row['id']);
            $this->setAlbumID($row['album_id']);
            $this->setFileName($row['filename']);
            $this->setAlbumFolder($row['foldername']);
            $this->setTitle($row['title']);
            $this->setDescription($row['description']);
            $this->createtime = $row['createtime'];
        }
    }
}

// vim: set ts=4:sw=4