/* Copyright 2022 Jaakko Keränen <jaakko.keranen@iki.fi>

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */

#include "canvas.h"
#include "render.h"
#include "video.h"

#ifndef A_ITALIC
#   define A_ITALIC 0
#endif

static iVisChar outside_;

iDefineTypeConstructionArgs(Canvas, (iInt2 size), size)
    
iLocalDef iRect clipRect_Canvas_(const iCanvas *d) {
    if (d->clipRect.size.x < 0 || d->clipRect.size.y < 0) {
        return (iRect){ zero_I2(), d->size };
    }
    return d->clipRect;
}

void init_Canvas(iCanvas *d, iInt2 size) {
    d->size = size;
    init_Array(&d->buf, sizeof(iVisChar));
    resize_Array(&d->buf, size.x * size.y);
    unsetClip_Canvas(d);
}

void deinit_Canvas(iCanvas *d) {
    deinit_Array(&d->buf);
}

void resize_Canvas(iCanvas *d, iInt2 size) {
    iCanvas *resized = new_Canvas(size);
    blit_Canvas(resized, d, (iRect){ zero_I2(), d->size }, zero_I2(), SDL_BLENDMODE_NONE);
    deinit_Canvas(d);
    *d = *resized;
}

void setClip_Canvas(iCanvas *d, iRect rect) {
    if (rect.size.x < 0 || rect.size.y < 0) {
        unsetClip_Canvas(d);
    }
    else {
        d->clipRect = intersect_Rect(rect, (iRect){ zero_I2(), d->size });
    }
}

void unsetClip_Canvas(iCanvas *d) {
    d->clipRect = init_Rect(-1, -1, -1, -1);
}

void clear_Canvas(iCanvas *d, int color) {
    const iVisChar clear = { .ch = ' ', .fg = 0, .bg = color, .attr = 0 };
    iForEach(Array, i, &d->buf) {
        *(iVisChar *) i.value = clear;
    }
}

void fillRect_Canvas(iCanvas *d, iRect rect, int color) {
    fillRectChar_Canvas(d, rect, color, ' ', 0);
}

void fillRectChar_Canvas(iCanvas *d, iRect rect, int bgColor, iChar ch, int fgColor) {
    iConstForEach(Rect, i, intersect_Rect(clipRect_Canvas_(d), rect)) {
        iVisChar *vis = at_Canvas(d, i.pos);
        if (bgColor != transparent_VisChar) {
            vis->bg = bgColor;
        }
        vis->fg = fgColor;
        vis->ch = ch;
        vis->attr = 0;
    }    
}

void setChar_Canvas(iCanvas *d, iInt2 pos, iChar ch, int color) {
    if (contains_Rect(clipBounds_Canvas(d), pos)) {
        iVisChar *vis = at_Array(&d->buf, pos.x + pos.y * d->size.x);
        vis->ch   = ch;
        vis->fg   = color;
        vis->attr = 0;
    }    
}

void drawHLine_Canvas(iCanvas *d, iInt2 pos, int width, iChar ch, int color) {
    const iRect bounds = clipRect_Canvas_(d);
    for (int x = pos.x; x < pos.x + width; x++) {
        iInt2 i = init_I2(x, pos.y);
        if (contains_Rect(bounds, i)) {
            iVisChar *vis = at_Canvas(d, i);
            vis->ch   = ch;
            vis->fg   = color;
            vis->attr = 0;
        }
    }    
}

void drawVLine_Canvas(iCanvas *d, iInt2 pos, int height, iChar ch, int color) {
    const iRect bounds = clipRect_Canvas_(d);
    for (int y = pos.y; y < pos.y + height; y++) {
        iInt2 i = init_I2(pos.x, y);
        if (contains_Rect(bounds, i)) {
            iVisChar *vis = at_Canvas(d, i);
            vis->ch   = ch;
            vis->fg   = color;
            vis->attr = 0;
        }
    }    
}

void drawRect_Canvas(iCanvas *d, iRect rect, int color) {
    drawVLine_Canvas(d, add_I2(topRight_Rect(rect), init_I2(-1, 1)), height_Rect(rect) - 2, 0x2502, color);
    drawHLine_Canvas(d, add_I2(bottomLeft_Rect(rect), init_I2(1, -1)), width_Rect(rect) - 2, 0x2500, color);
    drawVLine_Canvas(d, addY_I2(topLeft_Rect(rect), 1), height_Rect(rect) - 2, 0x2502, color);
    drawHLine_Canvas(d, addX_I2(topLeft_Rect(rect), 1), width_Rect(rect) - 2, 0x2500, color);
    setChar_Canvas(d, topLeft_Rect(rect), 0x250c, color);
    setChar_Canvas(d, addX_I2(topRight_Rect(rect), -1), 0x2510, color);
    setChar_Canvas(d, add_I2(bottomRight_Rect(rect), init1_I2(-1)), 0x2518, color);
    setChar_Canvas(d, addY_I2(bottomLeft_Rect(rect), -1), 0x2514, color);
}

void blit_Canvas(iCanvas *d, const iCanvas *src, iRect srcRect, iInt2 dst, SDL_BlendMode blend) {
    const iRect bounds = clipRect_Canvas_(d);
    /* Minimum edge. */ {
        int clip = 0;
        if (dst.x < left_Rect(bounds)) {
            clip = left_Rect(bounds) - dst.x;
            dst.x = left_Rect(bounds);
            srcRect.size.x -= clip;
            srcRect.pos.x += clip;
        }
        if (dst.y < top_Rect(bounds)) {
            clip = top_Rect(bounds) - dst.y;
            dst.y = top_Rect(bounds);
            srcRect.size.y -= clip;
            srcRect.pos.y += clip;
        }
    }
    /* Maximum edge. */ {
        int clip = 0;
        int x2 = dst.x + srcRect.size.x;
        if (x2 > right_Rect(bounds)) {
            clip = x2 - right_Rect(bounds);
            srcRect.size.x -= clip;
        }
        int y2 = dst.y + srcRect.size.y;
        if (y2 > bottom_Rect(bounds)) {
            clip = y2 - bottom_Rect(bounds);
            srcRect.size.y -= clip;
        }
    }
    if (srcRect.size.x <= 0 || srcRect.size.y <= 0) {
        return;
    }
    for (int row = 0; row < srcRect.size.y; row++) {
        const int dy = dst.y + row;
        if (dy < 0) continue;
        if (dy >= d->size.y) break;
        size_t n = iClamp(srcRect.size.x, 0, iMin(width_Rect(srcRect), d->size.x - dst.x));
        const iInt2 srcOrigin = addY_I2(srcRect.pos, row);
        const iInt2 dstOrigin = init_I2(dst.x, dy);
        const iVisChar *from = constAt_Canvas(src, srcOrigin);
        iVisChar *to = at_Canvas(d, dstOrigin);
        if (blend == SDL_BLENDMODE_BLEND) {
            for (size_t i = 0; i < n; i++) {
                const iInt2 dstPos = addX_I2(dstOrigin, i);
                if (!contains_Rect(bounds, dstPos)) {
                    continue;
                }
                const iVisChar *srcVis = constAt_Canvas(src, addX_I2(srcOrigin, i));
                iVisChar       *dstVis = at_Canvas(d, dstPos);
                if (srcVis->fg != transparent_VisChar && srcVis->ch) {
                    if (srcVis->bg != transparent_VisChar) {
                        dstVis->bg = srcVis->bg;
                    }
                    dstVis->ch   = srcVis->ch;
                    dstVis->fg   = srcVis->fg;
                    dstVis->attr = srcVis->attr;
                }
            }
        }
        else {
            iAssert(from != &outside_);
            iAssert(to != &outside_);
            memcpy(to, from, n * sizeof(iVisChar));
        }
    }
}

iLocalDef iBool isValidPos_Canvas_(const iCanvas *d, iInt2 pos) {
    if (any_Boolv(less_I2(pos, zero_I2())) || any_Boolv(greaterEqual_I2(pos, d->size))) {
        return iFalse;
    }
    return iTrue;
}

iVisChar *at_Canvas(iCanvas *d, iInt2 pos) {
    if (isValidPos_Canvas_(d, pos)) {
        return at_Array(&d->buf, pos.x + pos.y * d->size.x);
    }
    return &outside_;
}

const iVisChar *constAt_Canvas(const iCanvas *d, iInt2 pos) {
    if (isValidPos_Canvas_(d, pos)) {
        return constAt_Array(&d->buf, pos.x + pos.y * d->size.x);
    }
    return &outside_;
}

iRect clipBounds_Canvas(const iCanvas *d) {
    return clipRect_Canvas_(d);
}

void present_Canvas(const iCanvas *d, WINDOW *cwin) {
    for (int y = 0; y < d->size.y; y++) {
        int offset = 0;
        for (int x = 0; x < d->size.x; x++) {
            const iVisChar *vis = constAt_Canvas(d, init_I2(x + offset, y));
            int adv = width_Char(vis->ch);
            iMultibyteChar mbc;
            init_MultibyteChar(&mbc, vis->ch);
            attr_t attr = 0;
            uint32_t pair = SDL_GetColorPair(vis->ch ? vis->fg : transparent_VisChar, vis->bg);
            if (pair & A_REVERSE) {
                attr |= A_REVERSE;
                pair &= ~A_REVERSE;
            }
            if (pair & A_BOLD) {
                attr |= A_BOLD;
                pair &= ~A_BOLD;
            }
            if (vis->attr & reverse_VisCharAttribute) {
                attr ^= A_REVERSE;
            }
            if (vis->attr & bold_VisCharAttribute) {
                attr |= A_BOLD;
            }
            if (vis->attr & underline_VisCharAttribute) {
                attr |= A_UNDERLINE;
            }
            if (vis->attr & italic_VisCharAttribute) {
                attr |= A_ITALIC;
            }
            wmove(cwin, y, x);
            wattr_set(cwin, attr, pair & 0xff, NULL);
            waddstr(cwin, mbc.bytes);
            if (adv == 2) {
                waddch(cwin, ' ');
                x++;
            }
        }
    }
}
