"""
Database operations and models for pet pictures
"""

import sqlite3
from flask import current_app, g


def get_db():
    """Get database connection"""
    if 'db' not in g:
        g.db = sqlite3.connect("pet_pictures.db")
        g.db.row_factory = sqlite3.Row
    return g.db


def close_db(e=None):
    """Close database connection"""
    db = g.pop('db', None)
    if db is not None:
        db.close()


def init_db():
    """Initialize database with required tables"""
    db = get_db()
    db.execute(
        """
        CREATE TABLE IF NOT EXISTS pet_pictures (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            filename TEXT NOT NULL,
            subscriber_name TEXT NOT NULL,
            description TEXT,
            uploaded_at TIMESTAMP NOT NULL,
            posted BOOLEAN DEFAULT 0,
            likes INTEGER DEFAULT 0
        )
        """
    )
    db.commit()


class PetPicture:
    """Model for pet picture operations"""
    
    @staticmethod
    def get_all():
        """Get all pet pictures"""
        db = get_db()
        return db.execute(
            "SELECT * FROM pet_pictures ORDER BY uploaded_at DESC"
        ).fetchall()
    
    @staticmethod
    def get_posted():
        """Get only posted pet pictures"""
        db = get_db()
        return db.execute(
            "SELECT * FROM pet_pictures WHERE posted = 1 ORDER BY uploaded_at DESC"
        ).fetchall()
    
    @staticmethod
    def create(filename, subscriber_name, description, uploaded_at):
        """Create new pet picture record"""
        db = get_db()
        db.execute(
            "INSERT INTO pet_pictures (filename, subscriber_name, description, uploaded_at) VALUES (?, ?, ?, ?)",
            (filename, subscriber_name, description, uploaded_at)
        )
        db.commit()
    
    @staticmethod
    def mark_as_posted(picture_id):
        """Mark picture as posted"""
        db = get_db()
        db.execute("UPDATE pet_pictures SET posted = 1 WHERE id = ?", (picture_id,))
        db.commit()
    
    @staticmethod
    def update_likes(picture_id, increment=True):
        """Update like count for a picture"""
        db = get_db()
        if increment:
            db.execute("UPDATE pet_pictures SET likes = likes + 1 WHERE id = ?", (picture_id,))
        else:
            db.execute("UPDATE pet_pictures SET likes = likes - 1 WHERE id = ?", (picture_id,))
        db.commit()
    
    @staticmethod
    def get_like_count(picture_id):
        """Get current like count for a picture"""
        db = get_db()
        result = db.execute("SELECT likes FROM pet_pictures WHERE id = ?", (picture_id,)).fetchone()
        return result['likes'] if result else 0