All files / src/app/models pid.ts

85.61% Statements 357/417
77.27% Branches 68/88
78.04% Functions 32/41
85.5% Lines 354/414

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927            112x                             110x           110x       1320x         74x 74x     74x 74x 74x 74x 74x 74x                                                                               110x                                                             28x 28x                       88x 88x 88x 88x 88x     88x 70x 70x 70x 70x 70x     18x 18x 18x 18x 18x   88x 88x 18x   70x 30x   12x 6x   6x     6x 6x                 18x             88x   88x 70x 56x     14x                   14x 14x   14x 14x 14x 14x 14x 14x   14x   14x 14x 14x 14x 14x 14x     14x 14x 14x                 85x 85x 85x 85x 85x   85x 85x 85x 85x   85x   85x   85x 85x   85x 85x   85x   85x                                                                             7x 7x 7x 7x 7x   7x   7x       7x 7x       7x                         7x 7x 7x 7x   7x   7x         7x                           9x 9x 9x 9x   9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x   9x 9x 7x 7x       9x 3x 3x 3x                             7x 7x 7x 7x 7x   7x 7x   7x 7x   7x   7x 7x     7x 7x 7x 7x 7x 7x   7x 7x 7x   7x 7x 7x     7x 7x   7x 7x   7x 7x   7x 7x 7x     7x 7x 7x       7x 7x     7x 7x 7x 7x 7x 7x   7x                           2x                     7x 7x 7x 7x 7x 7x   7x 7x   7x 7x 7x     7x 7x 7x 7x 7x     7x   7x 847x 847x 847x 847x 847x 847x     7x 7x     7x       7x   7x       7x   7x   7x   7x   7x                                                                     4x     14x 14x 14x 14x   14x 14x     14x 7x 18x 7x 3x       14x 14x           110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x 110x                                   92x 92x 92x 92x 92x       92x           282x 282x   282x 282x 282x 266x 227x 227x 227x     39x       16x           16x       282x 282x                                         38x     8x 8x 8x 8x       103x 103x 103x 103x   103x     103x 103x     103x 103x 103x   103x 39x       39x 15x     24x         103x         103x         103x   103x   103x 103x   103x         103x             30x       75x 75x 75x 75x   75x   75x 75x 75x 75x 75x 75x 75x   75x   75x     75x         30x 30x 30x 30x 30x                                     4x       4x 4x 4x 4x 4x         2x 2x 2x 2x 60x 60x 1x 1x     2x 8x 8x         2x 18x 18x 1x 1x     2x 2x       4x 4x 4x 74x       4x 4x 8x     4x 4x 30x     4x   4x 4x 92x     4x               4x 4x 74x   4x         9x     9x 9x             9x 9x 9x       9x 282x     9x 224x     9x 28x     9x 75x            
import { Point, PointInterface, ViewWindow, Zone, Drawer, SurfaceStyle, TextStyle, DrawObject, ColorPalette, lightPalette, darkPalette, EdgeStyle } from './canvas';
import { SignalSample } from './signals';
import { Subject } from 'rxjs';
import { rgbToHex } from '../utils/utils';
 
export abstract class PIDElement{
    fontSize: number = 0.1;
    position: Point;
    name: string;
 
    abstract draw(context: CanvasRenderingContext2D, palette: ColorPalette, viewWindow: ViewWindow): void;
}
 
export class BaseComponentInterface{
    class: string;
    position: PointInterface;
    status_signal_id: string;
    command_signal_id: string;
}
 
 
export class Component extends PIDElement{
    statusSignalId: string;
    commandSignalId: string;
    statusSample?: SignalSample;
 
    // Registry to map types to classes
    private static componentRegistry: { [key: string]: typeof Component } = {};
 
    // Method to register a class for deserialization
    static registerComponent(type: string, componentClass: typeof Component) {
        Component.componentRegistry[type] = componentClass;
    }
 
     // Class method for deserializing the right component
    static deserialize(data: ComponentInterface): Component {
        const componentClass = Component.componentRegistry[data.class];
        Iif (!componentClass) {
        throw new Error(`Unknown component type: ${data.class}`);
        }
        const obj = Object.assign(new componentClass(), data);
        const position = new Point(data.position.x, data.position.y);
        obj.position = position;
        obj.statusSignalId = data.status_signal_id;
        obj.commandSignalId = data.command_signal_id;
        return obj;
    }
 
    draw(context: CanvasRenderingContext2D, palette: ColorPalette, viewWindow: ViewWindow){
        const position = viewWindow.canvasPoint(this.position);
        context.beginPath();
        const size = 20;
        context.rect(position.x-0.5*size, position.y-0.5*size, size, size);
        context.fillStyle = palette.foreground;
        context.fill();
        context.closePath();
    }
 
    drawImage(context: CanvasRenderingContext2D, viewWindow: ViewWindow, image:string, position:Point, width: number, height?:number, ){
 
        const imagePosition = viewWindow.canvasPoint(position);
        const img = new window.Image();
        img.src = 'assets/schematics/'+image;
 
        img.onload = () => {
            let imageHeight: number;
            const imageWidth = width / viewWindow.xScale;
            if (height === undefined){
                // Recompute height
                imageHeight = width / img.width * img.height;
            }
            else{
                imageHeight = height;
            }
            imageHeight /= viewWindow.yScale;
            context.drawImage(img, imagePosition.x-0.5*imageWidth, imagePosition.y-0.5*imageHeight, imageWidth, imageHeight);
 
        };
 
        img.onerror = () => {
            console.error('schematics: image cannot be found at '+img.src);
        };
 
 
 
    }
}
 
export class ImageInterface extends BaseComponentInterface{
    width: number;
    height: number;
    image: string;
 
}
 
export class Image extends Component{
    width: number;
    height?: number;
    image: string;
 
    override draw(context: CanvasRenderingContext2D, palette: ColorPalette, viewWindow: ViewWindow){
        this.drawImage(context, viewWindow, this.image, this.position, this.width);
    }
 
 
}
 
 
interface ValveInterface extends BaseComponentInterface{
    size: number;
    horizontal: boolean;
 
}
 
export class Valve extends Component{
    size: number;
    horizontal: boolean = true;
    onOff: boolean = true;
 
    // Class method for deserializing the right component
    static override deserialize(data: ValveInterface): Valve {
        const obj = super.deserialize(data) as Valve;
        obj.statusSignalId = data.status_signal_id;
        obj.commandSignalId = data.command_signal_id;
        return obj;
    }
 
 
    override draw(context: CanvasRenderingContext2D, palette:ColorPalette, viewWindow: ViewWindow){
        const position = viewWindow.canvasPoint(this.position);
        const size = viewWindow.size(this.size);
        const height = 0.75*size;
        const drawer = new Drawer(context);
        const fontSize = viewWindow.size(this.fontSize);
 
        let points: Point[];
        if (this.horizontal === true){
            const p1 = new Point(position.x-0.5*size, position.y-0.5*height);
            const p2 = new Point(position.x+0.5*size, position.y+0.5*height);
            const p3 = new Point(position.x+0.5*size, position.y-0.5*height);
            const p4 = new Point(position.x-0.5*size, position.y+0.5*height);
            points = [p1, p2, p3, p4, p1];
        }
        else{
            const p1 = new Point(position.x-0.5*height, position.y-0.5*size);
            const p2 = new Point(position.x+0.5*height, position.y+0.5*size);
            const p3 = new Point(position.x+0.5*height, position.y-0.5*size);
            const p4 = new Point(position.x-0.5*height, position.y+0.5*size);
            points = [p1, p3, p4, p2, p1];
        }
        let fillColor: string = palette.alert;
        if (this.statusSignalId === undefined){
            fillColor = palette.foreground;
        }
        else if (this.statusSample !== undefined){
            if (typeof this.statusSample.value == 'string'){
 
                if (this.statusSample.value === 'opened'){
                    fillColor = 'white';
                }
                else Iif (this.statusSample.value === 'intermediate'){
                    fillColor = 'grey';
                }
                else Eif (this.statusSample.value === 'closed'){
                    fillColor = 'black';
                }
                else if (this.statusSample.value === 'sensor-error'){
                    fillColor = 'red';
                }
                else{
                    console.log('unhandled', this.statusSample.value, this.name);
                }
           }
           else Iif (typeof this.statusSample.value == 'number'){
            const value = 255*this.statusSample.value/100;
            fillColor = rgbToHex(value, value, value);
           }
        }
 
 
        drawer.drawPolygon(points, new SurfaceStyle(fillColor, 1, palette.border));
 
        if (this.name !== undefined){
            if (this.horizontal === true){
                drawer.drawText(this.name, position.x, position.y - height, new TextStyle(palette.border), fontSize);
            }
            else{
                drawer.drawText(this.name, position.x + size, position.y, new TextStyle(palette.border, 'left'), fontSize);
            }
        }
 
    }
}
 
export class Regulator extends Valve{
 
    override draw(context: CanvasRenderingContext2D, palette:ColorPalette, viewWindow: ViewWindow){
        const position = viewWindow.canvasPoint(this.position);
        const size = viewWindow.size(this.size);
 
        context.beginPath();
        context.moveTo(position.x, position.y);
        context.lineTo(position.x, position.y - 1.5*size);
        context.lineTo(position.x + 0.8*size, position.y - 1.5*size);
        context.lineTo(position.x + 0.8*size, position.y);
        context.stroke();
 
        context.closePath();
 
        context.beginPath();
        context.fillStyle = palette.foreground;
        context.arc(position.x, position.y - 0.5*size, .6*size, 1.25*Math.PI, 1.75*Math.PI);
        context.stroke();
        context.fill();
        context.closePath();
 
        // Avoid yellow drawing
        const palette2 = structuredClone(palette);
        palette2.alert = palette.foreground;
        super.draw(context, palette2, viewWindow);
 
    }
}
 
export class Flange extends Component{
    size: number;
 
    override draw(context: CanvasRenderingContext2D, palette:ColorPalette, viewWindow: ViewWindow){
        const position = viewWindow.canvasPoint(this.position);
        const size = viewWindow.size(this.size);
        const gap = 0.25*size;
        context.strokeStyle = palette.border;
        context.fillStyle = palette.background;
 
        context.beginPath();
        context.rect(position.x-0.5*gap, position.y-0.5*size, gap, size);
        context.fill();
        context.closePath();
 
        context.lineWidth = 1;
 
        context.beginPath();
 
        context.moveTo(position.x-0.5*gap, position.y-0.5*size);
        context.lineTo(position.x-0.5*gap, position.y+0.5*size);
 
        context.moveTo(position.x+0.5*gap, position.y-0.5*size);
        context.lineTo(position.x+0.5*gap, position.y+0.5*size);
 
        context.stroke();
 
        context.closePath();
    }
}
 
interface VentInterface extends BaseComponentInterface{
    size: number;
 
}
 
export class Vent extends Component{
    size: number;
 
    override draw(context: CanvasRenderingContext2D, palette:ColorPalette, viewWindow: ViewWindow){
        const position = viewWindow.canvasPoint(this.position);
        const size = viewWindow.size(this.size);
        const drawer = new Drawer(context);
 
        context.strokeStyle = palette.border;
        context.fillStyle = palette.background;
 
        const points = [new Point(position.x, position.y - 0.5*size),
            new Point(position.x + 0.5*size, position.y),
            new Point(position.x, position.y + 0.5*size),
            new Point(position.x - 0.5*size, position.y)
                ];
        drawer.drawPolygon(points, new SurfaceStyle(palette.foreground, 1, palette.border));
        drawer.drawPath([points[0], points[2]], new EdgeStyle(1, palette.border));
    }
}
 
interface CheckValveInterface extends BaseComponentInterface{
    size: number;
 
}
 
export class AngleValve extends Component{
    size: number;
 
    override draw(context: CanvasRenderingContext2D, palette:ColorPalette, viewWindow: ViewWindow){
        const position = viewWindow.canvasPoint(this.position);
        const size = viewWindow.size(this.size);
        const height = 0.5*size;
        const drawer = new Drawer(context);
        const style = new SurfaceStyle(palette.foreground, 1, palette.border);
 
        drawer.drawRectangle(position.x - 0.5*size, position.y - 0.5*height, size, height, new SurfaceStyle(palette.background, 0));
 
        const points1 = [new Point(position.x, position.y),
            new Point(position.x - 0.25*size, position.y + 0.5*size),
            new Point(position.x + 0.25*size, position.y + 0.5*size),
                ];
        drawer.drawPolygon(points1, style);
        const points2 = [new Point(position.x, position.y),
            new Point(position.x + 0.5*size, position.y - 0.25*size),
            new Point(position.x + 0.5*size, position.y + 0.25*size),
                ];
        drawer.drawPolygon(points2, style);
    }
}
 
interface AngleValveInterface extends BaseComponentInterface{
    size: number;
 
}
 
export class CheckValve extends Component{
    size: number;
 
    override draw(context: CanvasRenderingContext2D, palette:ColorPalette, viewWindow: ViewWindow){
        const position = viewWindow.canvasPoint(this.position);
        const size = viewWindow.size(this.size);
        const height = 0.5*size;
        const drawer = new Drawer(context);
 
        drawer.drawRectangle(position.x - 0.5*size, position.y - 0.5*height, size, height, new SurfaceStyle(palette.background, 0));
 
        const points = [new Point(position.x - 0.5*size, position.y - 0.5*height),
            new Point(position.x - 0.5*size, position.y + 0.5*height),
            new Point(position.x + 0.5*size, position.y - 0.5*height),
            new Point(position.x + 0.5*size, position.y + 0.5*height)
                ];
        drawer.drawPath(points, new EdgeStyle(1, palette.border));
    }
}
 
interface VesselInterface extends BaseComponentInterface{
    height: number;
    width: number;
}
 
export class Vessel extends Component{
    height: number;
    width: number;
 
    override draw(context: CanvasRenderingContext2D, palette:ColorPalette, viewWindow: ViewWindow){
        const position = viewWindow.canvasPoint(this.position);
        const height = viewWindow.size(this.height);
        const width = viewWindow.size(this.width);
        const rectHeight = 0.8*height;
 
        const drawer = new Drawer(context);
        const style = new SurfaceStyle(palette.foreground, 1, palette.border);
        drawer.drawRectangle(position.x-0.5*width, position.y-0.5*rectHeight, width, rectHeight, style);
        const p1 = new Point(position.x-0.5*width, position.y-0.5*rectHeight);
        const p2 = new Point(position.x, position.y-0.5*height);
        const p3 = new Point(position.x+0.5*width, position.y-0.5*rectHeight);
        const p4 = new Point(position.x-0.5*width, position.y+0.5*rectHeight);
        const p5 = new Point(position.x, position.y+0.5*height);
        const p6 = new Point(position.x+0.5*width, position.y+0.5*rectHeight);
        drawer.drawArcFromPoints(p1, p2, p3, style);
        drawer.drawArcFromPoints(p4, p5, p6, style);
 
        const columnWidth = 0.05*width;
        if (this.statusSignalId !== undefined){
            const columnStyle = new SurfaceStyle(palette.background, 1, palette.border);
            drawer.drawRectangle(position.x-columnWidth-0.6*width, position.y-0.5*height, columnWidth, height, columnStyle);
        }
 
        // Water column
        if (this.statusSample !== undefined && (typeof this.statusSample.value == 'number')){
            const waterStyle = new SurfaceStyle('#35b5e8', 0);
            const waterHeight = height*this.statusSample.value/100;
            drawer.drawRectangle(position.x-columnWidth-0.6*width, position.y+0.5*height - waterHeight, columnWidth, waterHeight, waterStyle);
        }
    }
}
 
interface HybridRocketEngineInterface extends BaseComponentInterface{
    height: number;
    width: number;
}
 
export class HybridRocketEngine extends Component{
    height: number;
    width: number;
 
    override draw(context: CanvasRenderingContext2D, palette:ColorPalette, viewWindow: ViewWindow){
        const position = viewWindow.canvasPoint(this.position);
        const height = viewWindow.size(this.height);
        const width = viewWindow.size(this.width);
        const wallThickness = 0.1 * width;
        const chamberWidth = 2.5 * wallThickness;
 
        const nozzleWidth = 0.5*width;
        const nozzleHeight = 0.25*width;
 
        const nozzleHeadHeight = 0.3*nozzleHeight;
        const nozzleHeadWidth = 0.6*nozzleWidth;
 
        const drawer = new Drawer(context);
 
        const style = new SurfaceStyle(palette.foreground, 1, palette.border);
        const wallStyle = new SurfaceStyle("#1f1f1f", 1, palette.border);
 
 
        const p1 = new Point(position.x-0.5*width, position.y-0.5*height);
        const p2 = new Point(position.x-0.5*width, position.y+0.5*height-2*nozzleHeadHeight-nozzleHeight);
        const p3 = new Point(position.x-0.5*nozzleHeadWidth, position.y+0.5*height-nozzleHeight);
        const p4 = new Point(position.x-0.5*nozzleHeadWidth, position.y+0.5*height-nozzleHeadHeight-nozzleHeight);
        const p5 = new Point(position.x+0.5*(wallThickness-width), position.y+0.5*height-2*nozzleHeadHeight-nozzleHeight-wallThickness);
        const p6 = new Point(position.x+0.5*(wallThickness-width), position.y-0.5*height);
 
        const p6m = new Point(position.x-0.5*(wallThickness-width), position.y-0.5*height);
        const p5m = new Point(position.x-0.5*(wallThickness-width), position.y+0.5*height-2*nozzleHeadHeight-nozzleHeight-wallThickness);
        const p4m = new Point(position.x+0.5*nozzleHeadWidth, position.y+0.5*height-nozzleHeadHeight-nozzleHeight);
 
        const p1m = new Point(position.x+0.5*width, position.y-0.5*height);
        const p2m = new Point(position.x+0.5*width, position.y+0.5*height-2*nozzleHeadHeight-nozzleHeight);
        const p3m = new Point(position.x+0.5*nozzleHeadWidth, position.y+0.5*height-nozzleHeight);
 
 
        const points = [p1, p2, p3, p4, p5, p6, p1];
        drawer.drawPolygon(points, wallStyle);
 
        const pointsm = [p1m, p2m, p3m, p4m, p5m, p6m, p1m];
        drawer.drawPolygon(pointsm, wallStyle);
 
        const points2 = [p4, p5, p6, p6m, p5m, p4m, p4];
        drawer.drawPolygon(points2, style);
 
        const pc1 = new Point(position.x+0.5*(wallThickness+chamberWidth-width), position.y-0.5*height);
        const pc2 = new Point(position.x+0.5*(wallThickness+chamberWidth-width), position.y+0.5*height-2*nozzleHeadHeight-nozzleHeight-wallThickness);
        const pc3 = new Point(position.x-0.5*nozzleHeadWidth+0.5*chamberWidth, position.y+0.5*height-nozzleHeadHeight-nozzleHeight);
 
        //m
        const pc3m = new Point(position.x+0.5*nozzleHeadWidth-0.5*chamberWidth, position.y+0.5*height-nozzleHeadHeight-nozzleHeight);
        const pc2m = new Point(position.x-0.5*(wallThickness+chamberWidth-width), position.y+0.5*height-2*nozzleHeadHeight-nozzleHeight-wallThickness);
        const pc1m = new Point(position.x-0.5*(wallThickness+chamberWidth-width), position.y-0.5*height);
 
 
 
        const chamberPoints = [pc1, pc2, pc3, pc3m, pc2m, pc1m, pc1];
        drawer.drawPolygon(chamberPoints, wallStyle);
 
        // Nozzle
        const p1n = new Point(position.x-0.5*nozzleHeadWidth, position.y+0.5*height-nozzleHeight);
        const p2n = new Point(position.x-0.5*nozzleWidth, position.y+0.5*height);
        const p3n = new Point(position.x+0.5*nozzleWidth, position.y+0.5*height);
        const p4n = new Point(position.x+0.5*nozzleHeadWidth, position.y+0.5*height-nozzleHeight);
        const pointsNozzle = [p1n, p2n, p3n, p4n, p1n];
        drawer.drawPolygon(pointsNozzle, style);
 
        drawer.drawRectangle(position.x-0.5*nozzleHeadWidth, position.y+0.5*height-nozzleHeight-nozzleHeadHeight, nozzleHeadWidth, nozzleHeadHeight, style);
    }
}
 
export interface UmbilicalInterface extends BaseComponentInterface{
    size: number;
    horizontal: boolean;
    gap_signal_id: string;
    max_opening: number;
}
 
export class Umbilical extends Component{
    size: number;
    gapSignalId: string;
    max_opening: number = 1;
 
    // Class method for deserializing the right component
    static override deserialize(data: UmbilicalInterface): Umbilical {
        const obj = super.deserialize(data) as Umbilical;
        obj.gapSignalId = data.gap_signal_id;
        return obj;
    }
 
 
    override draw(context: CanvasRenderingContext2D, palette:ColorPalette, viewWindow: ViewWindow){
        const position = viewWindow.canvasPoint(this.position);
        const size = viewWindow.size(this.size);
        const height = 0.2*size;
        const numberWindings = 4;
        const numberPointPerWinding = 30;
        const drawer = new Drawer(context);
 
        const points1: Point[] = [];
        const points2: Point[] = [];
 
        const nPoints = numberPointPerWinding*numberWindings;
        let gap = 0;
        Iif(this.statusSample !== undefined &&  typeof(this.statusSample.value) == "number"){
            gap = this.statusSample.value;
        }
        const new_gap = Math.min(gap, this.max_opening)/this.max_opening*size/2;
        const x1 = position.x - 0.5*size;
        const x2 = position.x - 0.5*new_gap;
        const x3 = position.x + 0.5*new_gap;
        const x4 = position.x + 0.5*size;
 
        // Background
        drawer.drawRectangle(x1, position.y-0.5*height, size, height, new SurfaceStyle(palette.background, 0));
 
        for (let i=0;i<=nPoints;i++){
            const xl = (x2 - x1) * i/nPoints + x1;
            const yl = 0.5*height * Math.sin(i/nPoints*6.28*numberWindings) + position.y;
            const xr = (x4 - x3) * i/nPoints + x3;
            const yr = 0.5*height * Math.sin(i/nPoints*6.28*numberWindings) + position.y;
            points1.push(new Point(xl, yl));
            points2.push(new Point(xr, yr));
        }
 
        drawer.drawPath(points1, new EdgeStyle(1, palette.border));
        drawer.drawPath(points2, new EdgeStyle(1, palette.border));
 
        // Flanges
        const flangeL = [new Point(x1-0.1*size, position.y + 0.5*height),
                   new Point(x1, position.y + 0.5*height),
                   new Point(x1, position.y - 0.5*height),
                   new Point(x1-0.1*size, position.y - 0.5*height)];
        drawer.drawPath(flangeL, new EdgeStyle(1, palette.border));
 
        const flangeR = [new Point(x4+0.1*size, position.y + 0.5*height),
                   new Point(x4, position.y + 0.5*height),
                   new Point(x4, position.y - 0.5*height),
                   new Point(x4+0.1*size, position.y - 0.5*height)];
        drawer.drawPath(flangeR, new EdgeStyle(1, palette.border));
 
        const flangeML = [new Point(x2, position.y + 0.5*height),
                   new Point(x2, position.y - 0.5*height)];
        drawer.drawPath(flangeML, new EdgeStyle(1, palette.border));
 
        const flangeMR = [new Point(x3, position.y + 0.5*height),
                   new Point(x3, position.y - 0.5*height)];
        drawer.drawPath(flangeMR, new EdgeStyle(1, palette.border));
 
 
    }
}
 
 
export class DisconnectionBench extends Component{
    width: number;
 
 
    override draw(context: CanvasRenderingContext2D, palette:ColorPalette, viewWindow: ViewWindow){
        let trolleyPosition = 2200;
        if(this.statusSample !== undefined &&  typeof(this.statusSample.value) == "number"){
            trolleyPosition = this.statusSample.value;
        }
        const imageTrolleyPosition = new Point(this.position.x+trolleyPosition/2200*this.width*0.22-0.0325*this.width, this.position.y-0.054*this.width);
        this.drawImage(context, viewWindow, "disconnection-bench.png", this.position, this.width);
        this.drawImage(context, viewWindow, "disconnection-bench-trolley.png", imageTrolleyPosition, this.width/2.16);
    }
}
 
interface StatusLightColorOption {
    value: string;
    color: string;
}
 
interface StatusLightInterface extends BaseComponentInterface {
    value_type: string;
    options?: StatusLightColorOption[];
}
 
export class StatusLight extends Component {
    value_type: string;
    options?: StatusLightColorOption[];
    override fontSize: number = 0.2;
 
    override draw(context: CanvasRenderingContext2D, palette: ColorPalette, viewWindow: ViewWindow): void {
        const position = viewWindow.canvasPoint(this.position);
        const fontSize = viewWindow.size(this.fontSize);
        const drawer = new Drawer(context);
        const size = 0.3;
 
        let fillColor = "#b5b5b5";
        Iif (this.value_type === "bool" && (this.statusSample?.value ?? false)) {
            fillColor = "#f00";
        }
        else if (this.value_type === "enum") {
            const sampleValue = (this.statusSample?.value ?? "");
            const matchingOption = this.options?.find(option => option.value === sampleValue);
            if (matchingOption) {
                fillColor = matchingOption.color;
            }
        }
 
        drawer.drawCircle(position.x, position.y, viewWindow.size(size), new SurfaceStyle(fillColor, viewWindow.size(0.05), "#555"));
        drawer.drawText(this.name, position.x, position.y + viewWindow.size(size + this.fontSize), new TextStyle(palette.border), fontSize);
    }
}
 
type ComponentInterface = ImageInterface | ValveInterface | VesselInterface | HybridRocketEngineInterface | UmbilicalInterface | VentInterface | CheckValveInterface | AngleValveInterface | StatusLightInterface;
 
Component.registerComponent("image", Image);
Component.registerComponent("vessel", Vessel);
Component.registerComponent("valve", Valve);
Component.registerComponent("regulator", Regulator);
Component.registerComponent("flange", Flange);
Component.registerComponent("hybrid-rocket-engine", HybridRocketEngine);
Component.registerComponent("umbilical", Umbilical);
Component.registerComponent("vent", Vent);
Component.registerComponent("check-valve", CheckValve);
Component.registerComponent("angle-valve", AngleValve);
Component.registerComponent("disconnection-bench", DisconnectionBench);
Component.registerComponent("status-light", StatusLight);
 
interface PipeInterface{
    start: number;
    end: number;
    diameter?: number;
    horizontal?: boolean;
    middle?: boolean;
}
 
export class Pipe{
    start: PIDElement;
    end: PIDElement;
    diameter: number;
    horizontal: boolean;
    middle: boolean;
 
    constructor(start:PIDElement ,end:PIDElement, diameter: number=1, horizontal: boolean=true, middle: boolean=true){
        this.start = start;
        this.end = end;
        this.diameter = diameter;
        this.horizontal = horizontal;
        this.middle = middle;
    }
 
    static deserialize(pipeJson: PipeInterface, elements: PIDElement[]): Pipe{
        return new Pipe(elements[pipeJson["start"]], elements[pipeJson["end"]], pipeJson["diameter"],
            pipeJson["horizontal"], pipeJson["middle"]
        );
    }
 
    draw(context: CanvasRenderingContext2D, palette:ColorPalette, viewWindow: ViewWindow){
        const start = viewWindow.canvasPoint(this.start.position);
        const end = viewWindow.canvasPoint(this.end.position);
 
        const drawer = new Drawer(context);
        const points = [start];
        if (this.horizontal){
            if (this.middle){
                const x1 = 0.5*(start.x + end.x);
                points.push(new Point(x1, start.y));
                points.push(new Point(x1, end.y));
            }
            else{
                points.push(new Point(end.x, start.y));
            }
        }
        else{
            Iif (this.middle){
                const y1 = 0.5*(start.y + end.y);
                points.push(new Point(start.x, y1));
                points.push(new Point(end.x, y1));
            }
            else{
                points.push(new Point(start.x, end.y));
            }
 
        }
        points.push(end);
        drawer.drawPolygon(points, new SurfaceStyle(null, this.diameter, palette.border));
 
    }
 
}
 
interface SensorInterface{
    position: PointInterface;
    signal_id: string;
    value?: string;
    class?: string;
}
 
interface TapSensorInterface extends SensorInterface{
    symbol: string;
    y_offset: number;
}
 
export class Sensor extends PIDElement{
    signal_id: string;
    sample?: SignalSample;
    unit: string = '';
 
    static deserialize(sensorJson: SensorInterface): Sensor{
        const sensor = Object.assign(new Sensor(), sensorJson);
        const position = new Point(sensorJson["position"]['x'], sensorJson["position"]['y']);
        sensor.position = position;
        return sensor;
    }
 
    draw(context: CanvasRenderingContext2D, palette:ColorPalette, viewWindow: ViewWindow){
        const position = viewWindow.canvasPoint(this.position);
        const drawer = new Drawer(context);
        const fontSize = viewWindow.size(this.fontSize);
        context.font = context.font.replace(/(?<value>\d+\.?\d*)/, fontSize.toString());
 
        let numberLine = 3;
 
        //
        context.textAlign = 'center';
        context.textBaseline = 'middle';
 
        // Prepare data
        const signalName = this.signal_id.split('.')[1];
        let value = "--";
        let forcedValue = "";
 
        if (this.sample !== undefined){
            Iif (this.sample.forced_value !== null && this.sample.forced_value !== undefined){
                forcedValue = this.sample.forced_value.toString();
                numberLine += 1;
            }
            if (this.sample.value === undefined || this.sample.value === null){
                value = "--";
            }
            else{
                value = this.sample.value.toString();
            }
        }
 
        // Compute dimensions
        const width = Math.max(context.measureText(signalName).width,
                             context.measureText(value).width,
                             context.measureText(forcedValue).width,
                             context.measureText(this.unit).width) + 20;
 
        const height = fontSize * numberLine;
 
        // Draw
 
        // Hollow rectangle
        drawer.drawRectangle(position.x-0.5*width, position.y-0.5*height, width, height, new SurfaceStyle(palette.foreground, 1, palette.border));
 
        const textStyle1 = new TextStyle(palette.border);
 
        drawer.drawText(signalName, position.x, position.y+0.5*fontSize-0.5*height, textStyle1, fontSize);
        drawer.drawText(value, position.x, position.y+1.5*fontSize-0.5*height, textStyle1, fontSize);
 
        Iif (forcedValue !== ""){
            drawer.drawRectangle(position.x-0.5*width, position.y+0.5*height-2*fontSize, width, fontSize, new SurfaceStyle(palette.alert, 0));
            drawer.drawText(forcedValue, position.x, position.y+2.5*fontSize-0.5*height, textStyle1, fontSize);
 
        }
        drawer.drawText(this.unit, position.x, position.y+(numberLine-.5)*fontSize-0.5*height, textStyle1, fontSize);
 
    }
 
}
 
class TapSensor extends Sensor{
    symbol: string = '';
    yOffset: number;
 
    override draw(context: CanvasRenderingContext2D, palette: ColorPalette, viewWindow: ViewWindow): void {
        const position = viewWindow.canvasPoint(this.position);
        const circlePosition = viewWindow.canvasPoint(new Point(this.position.x, this.position.y + this.yOffset));
        const yOffset = viewWindow.size(this.yOffset);
        const fontSize = viewWindow.size(this.fontSize);
 
        const drawer = new Drawer(context);
 
        context.lineWidth = 1;
        context.beginPath();
        context.moveTo(position.x, position.y);
        context.lineTo(circlePosition.x, circlePosition.y);
        context.strokeStyle = palette.border;
        context.stroke();
        context.closePath();
 
        drawer.drawCircle(circlePosition.x, circlePosition.y, 0.4*yOffset, new SurfaceStyle(palette.foreground, 2, "red"));
 
        drawer.drawText(this.symbol, circlePosition.x, circlePosition.y, new TextStyle(palette.border), fontSize);
 
 
        super.draw(context, palette, viewWindow);
 
    }
 
    static override deserialize(sensorJson: TapSensorInterface): TapSensor{
        const sensor = Object.assign(new TapSensor(), sensorJson);
        const position = new Point(sensorJson["position"]['x'], sensorJson["position"]['y']);
        sensor.position = position;
        sensor.yOffset = sensorJson["y_offset"];
        return sensor;
    }
}
 
 
export interface PIDInterface{
    components: ComponentInterface[];
    pipes: PipeInterface[];
    sensors: SensorInterface[];
    tap_sensors: TapSensorInterface[];
}
 
 
 
export class PID extends DrawObject{
    components: Component[];
    pipes: Pipe[];
    sensors: Sensor[];
    tapSensors: TapSensor[];
    selectedItem: Subject<Component | Sensor | null> = new Subject();
 
    constructor(components: Component[], pipes: Pipe[], sensors: Sensor[],
         tapSensors: TapSensor[]){
        super();
        this.components = components;
        this.pipes = pipes;
        this.sensors = sensors;
        this.tapSensors = tapSensors;
 
    }
 
    override mouseDownCallback(clickPoint: Point, viewWindow: ViewWindow){
        const clickPoint2 = viewWindow.zonePoint(clickPoint);
        let distance = Infinity;
        let bestItem: Component | Sensor | null = null;
        for (const component of this.components){
            const compDistance = clickPoint2.distance(component.position);
            if (compDistance < distance && compDistance < 0.3){// Todo: adapt this from scene size of view window size and from component bounding box
                distance = compDistance;
                bestItem = component;
            }
        }
        for (const sensor of this.sensors){
            const compDistance = clickPoint2.distance(sensor.position);
            Iif (compDistance < distance && compDistance < 0.3){// Todo: adapt this from scene size of view window size and from component bounding box
                distance = compDistance;
                bestItem = sensor;
            }
        }
        for (const tapSensor of this.tapSensors){
            const compDistance = clickPoint2.distance(tapSensor.position);
            if (compDistance < distance && compDistance < 0.3){// Todo: adapt this from scene size of view window size and from component bounding box
                distance = compDistance;
                bestItem = tapSensor;
            }
        }
        this.selectedItem.next(bestItem);
        return bestItem === null;
    }
 
    static deserialize(jsonPid: PIDInterface): PID{
        const components: Component[] = [];
        let refs: PIDElement[] = [];
        for (const componentJson of jsonPid['components']){
          components.push(Component.deserialize(componentJson));
        }
 
 
        const sensors: Sensor[] = [];
        for (const sensor of jsonPid['sensors']){
            sensors.push(Sensor.deserialize(sensor));
        }
 
        const tapSensors: TapSensor[] = [];
        for (const sensor of jsonPid['tap_sensors']){
            tapSensors.push(TapSensor.deserialize(sensor));
        }
 
        refs = refs.concat(components, sensors, tapSensors);
 
        const pipes: Pipe[] = [];
        for (const pipeJson of jsonPid['pipes']){
            pipes.push(Pipe.deserialize(pipeJson, refs));
          }
 
        return new PID(components, pipes, sensors, tapSensors);
 
    }
 
 
 
 
    override get zone(): Zone{
        const points: Point[] = [];
        for (const component of this.components){
            points.push(component.position);
        }
        return Zone.fromPoints(points);
    }
 
    override draw(context: CanvasRenderingContext2D, viewWindow: ViewWindow){
 
        const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
 
 
        let palette = lightPalette;
        Iif (isDarkMode){
            palette = darkPalette;
        }
 
 
 
        // Drawing background
        context.rect(0, 0, context.canvas.width, context.canvas.height);
        context.fillStyle = palette.background;
        context.fill();
 
 
 
        for (const pipe of this.pipes){
            pipe.draw(context, palette, viewWindow);
        }
 
        for (const component of this.components){
            component.draw(context, palette, viewWindow);
        }
 
        for (const sensor of this.sensors){
            sensor.draw(context, palette, viewWindow);
        }
 
        for (const sensor of this.tapSensors){
            sensor.draw(context, palette, viewWindow);
        }
 
    }
 
}