/*
Copyright 2011 Frans van den Bergh. All rights reserved.

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 Frans van den Bergh ''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 Frans van den Bergh 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.

The views and conclusions contained in the software and documentation are those of the
authors and should not be interpreted as representing official policies, either expressed
or implied, of the Council for Scientific and Industrial Research (CSIR).
*/
#ifndef SVG_PAGE_LENSGRID_SLIDE_H
#define SVG_PAGE_LENSGRID_SLIDE_H

#include "svg_page.h"
#include "include/mtf50_edge_quality_rating.h"
#include "lightweight_polygon.h"
#include "svg_poly_thorlogo.h"
#include "svg_poly_thorserial.h"

#include <vector>
#include <cmath>
using std::vector;
using std::pair;
using std::make_pair;

#ifndef SQR
#define SQR(x) ((x)*(x))
#endif

// Layout intended for microscope slides, so scale is in 10nm increments
constexpr double slide_scale = 1e3; // should be 1e9
constexpr double polys_scale = 0.45 * 10 / slide_scale; // we want slide*scale * polys_scale ~= 100, used only for generate_rectangle inputs
constexpr double fixed_aspect = 1.0/1.332;

class Target {
  public:
    Target(double scale, double off_x, double off_y)
    : scale(scale), off(off_x, off_y) {

    }

    double scale;
    dPoint off;
};

class Svg_page_lensgrid_slide : public Svg_page {
  public:
    Svg_page_lensgrid_slide(const string& page_spec, const string& fname, bool dump_polys=false) 
    : Svg_page(page_spec, fname, slide_scale), centre(0.5, 0.5*fixed_aspect),
      off(0), scale(10.0/100), local_scale(1.0), local_off(0, 0), dump_polys(dump_polys) {

        if (dump_polys) {
            poly_fout = fopen("polys.txt", "wt");
        }
    }

    virtual ~Svg_page_lensgrid_slide() {
        if (dump_polys) {
            fclose(poly_fout);
        }
    }
    
    void render(void) {
        constexpr double target_aspect_ratio = 1.0/fixed_aspect;
        constexpr int hcols = 4;
        constexpr int cols = 2 * hcols + 1;
        const int hrows = (int)lrint(hcols / target_aspect_ratio);
        const int rows = 2 * hrows + 1;

        printf("calculated rows x cols = %d x %d\n", rows, cols);

        constexpr double base_mag = 2.5;
        constexpr double base_mag_width = 5752;
        constexpr double fixed_pw = 76200;
        constexpr double base_scale = base_mag_width/fixed_pw * base_mag;
        const double midy = 0.5 * height_mm / width_mm;
        

        vector<Target> targets = {
            {2.5, 0.5 - 14750/fixed_pw, midy},
            {5,   0.5 - 6250/fixed_pw, midy},
            {10,  0.5, midy},
            {20,  0.5 + 5125/fixed_pw, midy},
            {50,  0.5 + 8650/fixed_pw, midy},
            {100, 0.5 + 10875/fixed_pw, midy}
        };

        for (const auto& t: targets) {
            local_scale = base_scale / t.scale;
            local_off = t.off;
            local_off.x -= 0.5 * local_scale; // center target horizontally
            local_off.y -= 0.5 * local_scale / target_aspect_ratio; // center target vertically
            printf("local scale = %lf, offset = (%lf, %lf)\n", local_scale, local_off.x, local_off.y);
            grid(0.12, rows, cols);
            limit_polys = true;
        }

        draw_logo(30168, 1448, thorlogo_pts);
        draw_logo(51388, 22150, thorserial_pts);
    }
    
  protected:
    virtual dPoint project(double x, double y, [[maybe_unused]] bool silent=false) {
        
        x = (local_scale*x + local_off.x)*width;
        y = (local_scale*y + local_off.y)*width;
        
        return dPoint(x, y);
    }

    double quant_angle(double x) {
        double quad1 = fabs(fmod(x, M_PI/2.0));
        if (quad1 > M_PI/4.0) {
            quad1 = M_PI/2.0 - quad1;
        }
        quad1 = quad1 / M_PI * 180;
        return quad1;
    }
    
    dPoint rotate(const dPoint& d, double theta) {
        dPoint r;
        r.x = cos(theta) * d.x - sin(theta) * d.y;
        r.y = sin(theta) * d.x + cos(theta) * d.y;
        return r;
    }
    
    bool place_trapezoid(double xpos, double ypos, double width, double angle_thresh) {
        constexpr double max_bias = 5.0/180.0 * M_PI;
        enum class state_t {
            TANGENTIAL,
            RADIAL1,
            RADIAL2,
            CONVERGED
        };

        state_t state = state_t::TANGENTIAL;

        vector<dPoint> coords(4);
        
        bool done = false;
        int tries = 0;
        int last_change = 0;
        double bias_angle1 = 0;
        double bias_sign1 = 1;
        double bias_angle2 = 0;
        double bias_sign2 = 1;
        double bias_angle3 = 0;
        double bias_sign3 = 1;
        static int trap_id = 0;
        do {
            dPoint delta = dPoint(xpos, ypos) - centre;
            
            double norm = sqrt(delta.x*delta.x + delta.y*delta.y);
            delta.x /= norm;
            delta.y /= norm;
            
            dPoint omx = dPoint(xpos + delta.x*width*sqrt(0.5), ypos + delta.y*width*sqrt(0.5));
            dPoint tang = dPoint(-delta.y, delta.x);

            tang = rotate(tang, bias_angle1 * bias_sign1);
            
            dPoint tl(omx.x - 0.5*width*tang.x, omx.y - 0.5*width*tang.y);
            dPoint p = project(tl.x, tl.y);
            coords[0] = p;
            
            dPoint rad = tl - centre;
            norm = sqrt(rad.x*rad.x + rad.y*rad.y);
            rad.x /= norm;
            rad.y /= norm;
            rad = rotate(rad, bias_angle2 * bias_sign2);
            
            dPoint bl(tl.x - rad.x*width, tl.y - rad.y*width);
            p = project(bl.x, bl.y);
            coords[1] = p;
            
            dPoint tr(omx.x + 0.5*width*tang.x, omx.y + 0.5*width*tang.y);
            
            rad = tr - centre;
            norm = sqrt(rad.x*rad.x + rad.y*rad.y);
            rad.x /= norm;
            rad.y /= norm;
            rad = rotate(rad, bias_angle3 * bias_sign3);

            dPoint br(tr.x - rad.x*width, tr.y - rad.y*width);
            p = project(br.x, br.y);
            coords[2] = p;
            
            p = project(tr.x, tr.y);
            coords[3] = p;
            
            double angles[4];
            for (int i=0; i < 4; i++) {
                int next = (i + 1) % 4;
                double angle = atan2(fabs(double(coords[i].y - coords[next].y)), fabs(double(coords[i].x - coords[next].x)));
                angle *= 180.0/M_PI;
                if (angle > 45) {
                    angle = 90 - angle;
                }
                // identify which edge this is
                int j = -1;
                switch(i) {
                case 0: j = 3; break;
                case 1: j = 0; break;
                case 2: j = 2; break;
                case 3: j = 1; break;
                }
                angles[j] = angle;
            }

            switch (state) {
            case state_t::TANGENTIAL:
                if (angles[0] < angle_thresh || angles[0] > 43 || fabs(angles[0] - 26.565) < 2 || fabs(angles[0] - 14.036) < 1 || fabs(angles[0] - 33.69) < 1 ||
                    angles[1] < angle_thresh || angles[1] > 43 || fabs(angles[1] - 26.565) < 2 || fabs(angles[1] - 14.036) < 1 || fabs(angles[1] - 33.69) < 1) { 
                    if (tries == 0 || (tries % 2) == 0) {
                        bias_angle1 += 0.005 / 180.0 * M_PI;
                    } else {
                        bias_sign1 = -1 * bias_sign1;
                    }
                    last_change = tries;
                } else {
                    state = state_t::RADIAL1;
                }
                break;
            case state_t::RADIAL1:
                if (fabs(angles[2]) < 4 || fabs(angles[2] - 45) < 2 || fabs(angles[2] - 26.565) < 2 ||
                    fabs(angles[2] - 14.036) < 1 || fabs(angles[2] - 33.69) < 1) {
                    if (tries == 0 || (tries % 2) == 0) {
                        bias_angle3 += 0.005 / 180.0 * M_PI;
                    } else {
                        bias_sign3 = -1 * bias_sign3;
                    }
                    last_change = tries;
                } else {
                    state = state_t::RADIAL2;
                }
                break;
            case state_t::RADIAL2:
                if (fabs(angles[3]) < 4 || fabs(angles[3] - 45) < 2 || fabs(angles[3] - 26.565) < 2 ||
                    fabs(angles[3] - 14.036) < 1 || fabs(angles[3] - 33.69) < 1) {
                    if (tries == 0 || (tries % 2) == 0) {
                        bias_angle2 += 0.005 / 180.0 * M_PI;
                    } else {
                        bias_sign2 = -1 * bias_sign2;
                    }
                    last_change = tries;
                } else {
                    state = state_t::CONVERGED;
                }
                break;
            case state_t::CONVERGED:
                break;
            }
            
            
            tries++;
            if (state == state_t::CONVERGED || tries > last_change+3 || bias_angle1 > max_bias ||
                bias_angle2 > max_bias || bias_angle3 > max_bias) {
                    done = true;
            }
        } while (!done);
        
        if ((bias_angle1 > 0 || bias_angle2 > 0 || bias_angle3 > 0)) {
            printf("trap %3d: a1 = %8.4f, a2 = %8.4f a3 = %8.4f\n", trap_id, 
                bias_sign1 * bias_angle1 / M_PI * 180,
                bias_sign2 * bias_angle2 / M_PI * 180,
                bias_sign3 * bias_angle3 / M_PI * 180
            );
        }

        trap_id++;

        fprintf(fout, "  <polygon points=\"%.6lf,%.6lf ", coords[0].x, coords[0].y);
        fprintf(fout, "%.6lf,%.6lf ", coords[1].x, coords[1].y);
        fprintf(fout, "%.6lf,%.6lf ", coords[2].x, coords[2].y);
        fprintf(fout, "%.6lf,%.6lf\" style=\"%s\"/>\n", coords[3].x, coords[3].y, style.c_str());
        
        if (dump_polys && !limit_polys) {
            fprintf(poly_fout, "4\n%le %le\n", polys_scale*(coords[0].y*scale + off), polys_scale*(coords[0].x*scale + off));
            fprintf(poly_fout, "%le %le\n", polys_scale*(coords[1].y*scale + off), polys_scale*(coords[1].x*scale + off));
            fprintf(poly_fout, "%le %le\n", polys_scale*(coords[2].y*scale + off), polys_scale*(coords[2].x*scale + off));
            fprintf(poly_fout, "%le %le\n", polys_scale*(coords[3].y*scale + off), polys_scale*(coords[3].x*scale + off));
        }
        
        return false;
    }
    
    void grid(double swidth, size_t nrows, size_t ncols) {
        const double aspect = fixed_aspect;
        
        const double phi = 1.9/180.0*M_PI;
        for (int row=0; row < (int)nrows; row++) {
            for (int col=0; col < (int)ncols; col++) {
                if (row == (int)nrows/2 && col == (int)ncols/2) continue;

                double sx = (col-int(ncols)/2)/double(ncols)*0.93;
                double sy = aspect*(row-int(nrows)/2)/double(nrows)*0.93;
                double rx = sx*cos(phi) - sy*sin(phi);
                double ry = sx*sin(phi) + sy*cos(phi);
                bool overlapped = place_trapezoid(
                    0.5 + rx,
                    0.5*aspect + ry,
                    swidth*sqrt(0.5)*aspect,
                    (col == (int)ncols/2) || (row == (int)nrows/2) ? 5 : 1.5
                );
                
                if (overlapped) {
                    double offset = 3.0;
                    if (abs(row - (int)nrows/2) <= 1 || abs(col - (int)ncols/2) <= 1) {
                        offset = 15.0;
                    }
                    for (double dp=0; overlapped && dp < offset/180.0*M_PI; dp += 0.25/180.0*M_PI) {
                        rx = sx*cos(phi + dp) - sy*sin(phi + dp);
                        ry = sx*sin(phi + dp) + sy*cos(phi + dp);
                        
                        overlapped = place_trapezoid(
                            0.5 + rx,
                            0.5*aspect + ry,
                            swidth*sqrt(0.5)*aspect,
                            (col == (int)ncols/2) || (row == (int)nrows/2) ? 5 : 1.5
                        );
                        
                        if (overlapped) {
                            rx = sx*cos(phi - dp) - sy*sin(phi - dp);
                            ry = sx*sin(phi - dp) + sy*cos(phi - dp);
                            
                            overlapped = place_trapezoid(
                                0.5 + rx,
                                0.5*aspect + ry,
                                swidth*sqrt(0.5)*aspect,
                                (col == (int)ncols/2) || (row == (int)nrows/2) ? 5 : 1.5
                            );
                        }
                    }
                }
            }
        }
        
        constexpr double center_square_angle = 50/180.0 * M_PI;
        rotated_square(0.5, 0.5*aspect, 0.5*swidth/sqrt(2.0), center_square_angle);
        rotated_square_poly(0.5, 0.5*aspect, 0.5*swidth/sqrt(2.0), center_square_angle);

        #ifdef SHOW_OUTLINES
        dPoint rtl = project(0, 0);
        dPoint rbr = project(1.0, 1.0 * fixed_aspect);
        outline_rect(rtl.x, rtl.y, rbr.x - rtl.x, rbr.y - rtl.y);
        #endif
    }

    void outline_rect(double tlx, double tly, double width, double height) {
        fprintf(fout, "  <rect x=\"%lf\" y=\"%lf\" width=\"%lf\" height=\"%lf\" style=\"fill:none;stroke:black;stroke-width:%lf\"/>\n",
            tlx, tly, width, height, local_scale * 1e5
        );
    }

    void rotated_square_poly(double tlx, double tly, double bwidth, double angle) {
        if (dump_polys && !limit_polys) {
            dPoint p = project(tlx + bwidth*cos(angle), tly + bwidth*sin(angle));
            fprintf(poly_fout, "4\n%.3lf %.3lf\n", polys_scale*(p.y*scale + off), polys_scale*(p.x*scale + off));
            p = project(tlx + bwidth*cos(angle+M_PI/2.0), tly + bwidth*sin(angle+M_PI/2.0));
            fprintf(poly_fout, "%.3lf %.3lf\n", polys_scale*(p.y*scale + off), polys_scale*(p.x*scale + off));
            p = project(tlx + bwidth*cos(angle+M_PI), tly + bwidth*sin(angle+M_PI));
            fprintf(poly_fout, "%.3lf %.3lf\n", polys_scale*(p.y*scale + off), polys_scale*(p.x*scale + off));
            p = project(tlx + bwidth*cos(angle+1.5*M_PI), tly + bwidth*sin(angle+1.5*M_PI));
            fprintf(poly_fout, "%.3lf %.3lf\n", polys_scale*(p.y*scale + off), polys_scale*(p.x*scale + off));
        }
    }

    void draw_logo(double offset_x, double offset_y, const vector<vector<double>>& poly_pts) {
        constexpr double fontscale = 1e3;
        #ifdef DUMP_MIN
        double minx = 1e20;
        double miny = 1e20;
        #endif
        
        for (const auto& p: poly_pts) {
            fprintf(fout, "  <polygon points=\" ");
            for (size_t pi=0; pi < p.size(); pi += 2) {
                #ifdef DUMP_MIN
                minx = std::min(minx, p[pi]);
                miny = std::min(miny, p[pi+1]);
                #endif
                fprintf(fout, "%.3lf,%.3lf ", p[pi] * fontscale + offset_x * fontscale, p[pi+1] * fontscale + offset_y * fontscale);
            }
            fprintf(fout, "\" style=\"%s\"/>\n", style.c_str());
        }
        #ifdef DUMP_MIN
        printf("minx=%lf, miny=%lf\n", minx, miny);
        #endif
    }
    
    dPoint centre;
    double off;
    double scale;
    double local_scale;
    dPoint local_off;
    bool dump_polys;
    bool limit_polys = false;
    FILE* poly_fout;
    
    vector<Convex_polygon> existing_trapezoids;
};

#endif
